text stringlengths 8 4.13M |
|---|
//
// Author: Shareef Abdoul-Raheem
// File: ast_processor.rs
//
use crate::ASTNodeLiteral;
use crate::ASTNodeRoot;
use crate::ASTNodeTag;
use crate::ASTNodeText;
pub trait IASTProcessor {
fn has_error(&mut self) -> bool;
fn visit_begin_root(&mut self, root_node: &ASTNodeRoot) -> ();
fn visit_begin_tag(&mut self, tag_node: &ASTNodeTag) -> ();
fn visit_text(&mut self, text_node: &ASTNodeText) -> ();
fn visit_literal(&mut self, literal_node: &ASTNodeLiteral) -> ();
fn visit_end_tag(&mut self, tag_node: &ASTNodeTag) -> ();
fn visit_end_root(&mut self, root_node: &ASTNodeRoot) -> ();
}
|
pub mod runner;
mod core;
|
//! A generic trait based interface for abstracting over various schemes for
//! concurrent memory reclamation.
//!
//! # Memory Management in Rust
//!
//! Unlike garbage collected languages such as *Go* or *Java*, memory
//! management in *Rust* is primarily scope or ownership based and more akin to
//! *C++*.
//! Rust's ownership model in combination with the standard library's smart
//! pointer types `Box`, `Rc` and `Arc` make memory management as painless as
//! possible and are able to handle the vast majority of use-cases, while at the
//! same time preventing the classic memory bugs such as *use-after-free*,
//! *double-free* or memory leaks.
//! Consequently, there is usually little need for the relatively small
//! additional comfort provided by a fully automated **Garbage Collector** (GC).
//!
//! ## The Need for Automatic Memory Reclamation
//!
//! In the domain of concurrent lock-free data structures, however, the
//! aforementioned memory management schemes are insufficient for determining,
//! when a removed entry can be actually dropped and de-allocated:
//! Just because an entry has been removed (*unlinked*) from some shared data
//! structure does not guarantee, that no other thread could still be in the
//! process of reading that same entry at the same time.
//! This is due to the possible existence of stale references that were created
//! by other threads before the unlinking occurred.
//! The only fact that can be ascertained, due to nature of atomic *swap* and
//! *compare-and-swap* operations, is that other threads can not acquire *new*
//! references after an entry has been unlinked.
//!
//! ## Extending the Grace Period
//!
//! Concurrent memory reclamation schemes work by granting every value
//! (*record*) earmarked for deletion (*retired*) a certain **grace period**
//! before being actually dropped and de-allocated.
//! During this period the value will be cached and can still be safely read by
//! other threads with live references to it, but no new references must be
//! possible.
//! Determining the exact length of this grace period is up to each individual
//! reclamation scheme.
//! It is usually either not possible or not practical to determine the exact
//! moment at which it becomes safe to reclaim a retired.
//! Hence, reclamation schemes commonly tend to only guarantee grace periods
//! that are *at least* as long as to ensure no references can possibly exist
//! afterwards.
//!
//! # The Reclaim Interface
//!
//! Lock-free data structures are usually required to work on atomic pointers to
//! heap allocated memory.
//! This is due to the restrictions of atomic CPU instructions to machine-word
//! sized values, such as pointers.
//! Working with raw pointers is inherently *unsafe* in the Rust sense.
//! Consequently, this crate avoids and discourages the use of raw pointers as
//! much as possible in favor of safer abstractions with stricter constraints
//! for their usage.
//! In effect, the vast majority of this crate's public API is safe to use under
//! any circumstances.
//! This, however, is achieved by shifting and concentrating the burden of
//! manually maintaining safety invariants into one specific key aspect:
//! The retiring (and eventual reclamation) of records.
//!
//! ## Traits and Types
//!
//! The `reclaim` crate primarily exposes four different traits, which are
//! relevant for users of generic code and implementors of reclamation schemes
//! alike.
//! The first trait is [`Reclaim`], which provides generic functionality for
//! retiring records.
//! Note, that this trait does not presume the presence of an operating system
//! and functionality like thread local storage.
//! Hence, this trait can even be used in `#[no_std]` environments.
//! However, in order to use this trait's associated methods, an explicit
//! reference to the current thread's (local) state is required.
//! For environments with implicit access to thread local storage, the
//! [`GlobalReclaim`] trait exists as an extension to [`Reclaim`].
//! This trait additionally requires an associated type
//! [`Guard`][GlobalReclaim::Guard], which must implement both the [`Default`]
//! and the [`Protect`] trait.
//!
//! Types implementing the [`Protect`] trait can be used to safely read values
//! from shared memory that are subsequently safe from concurrent reclamation
//! and can hence be safely de-referenced.
//! Note that a single guard can only protect one value at a time.
//! This follows the design of many reclamation schemes, such as *hazard
//! pointers*.
//! This is represented by the requirement to pass a *mutable* reference to a
//! guard in order to safely load a shared value.
//!
//! Some reclamation schemes (e.g. epoch based ones) do not require individual
//! protection of values, but instead protect arbitrary numbers of shared at
//! once.
//! The guard types for these schemes can additionally implement the
//! [`ProtectRegion`] trait.
//! Such guards do not have to carry any state and protect values simply by
//! their existence.
//! Consequently, it is also possible to call eg [`Atomic::load`] with a shared
//! reference to a guard implementing that trait.
//!
//! ## The `Atomic` Type
//!
//! The [`Atomic`] markable concurrent pointer type is the main point of
//! interaction with this crate.
//! It can only be safely created as a `null` pointer or with valid heap
//! allocation backing it up.
//! It supports all common atomic operations like `load`, `store`,
//! `compare_exchange`, etc.
//! The key aspect of this type is that together with a guard, shared values
//! can be safely loaded and de-referenced while other threads can concurrently
//! reclaim removed values.
//! In addition to the [`Shared`] type, which represents a shared reference that
//! is protected from reclamation, other atomic operations can yield
//! [`Unprotected`] or [`Unlinked`] values.
//! The former are explicitly not protected from reclamation and can be loaded
//! without any guards.
//! They are not safe to de-reference, but can be used to e.g. swing a pointer
//! from one linked list node to another.
//! [`Unlinked`] values are the result of *swap* or *compare-and-swap*
//! operations and represent values/references to which no new references can be
//! acquired any more by other threads.
//! They are like *owned* values that are also borrowed, since other threads may
//! still reference them.
//! All of these three different types are guaranteed to never be null at the
//! type level.
//!
//! ## Marked Pointer & Reference Types
//!
//! It is a ubiquitous technique in lock-free programming to use the lower bits
//! of a pointer address to store additional information alongside an address.
//! Common use-cases are ABA problem mitigation or to mark a node of a linked
//! list for removal.
//!
//! Accordingly, this crate allows all pointer and reference types
//! ([`MarkedPtr`], [`Shared`], etc.) to be marked.
//! The number of usable mark bits is encoded in the type itself as a generic
//! parameter `N`.
//! However, the number of available mark bits has a physical upper bound, which
//! is dictated by the alignment of the pointed-to type.
//! For instance, a `bool` has an alignment of 1, hence pointers to boolean
//! values can not, in fact, be marked.
//! On a 64-bit system, an `usize` has an alignment of 8, which means a pointer
//! to one can use up to 3 mark bits.
//! Since the number `N` is encoded in the pointer types themselves, attempting
//! to declare types with more available mark bits than what the pointed-to
//! type's alignment will lead to a (currently fairly cryptic) compile time
//! error.
//! Note, that tags are allowed to overflow. This can lead to surprising results
//! when attempting to e.g. mark a pointer that is declared to support zero mark
//! bits (`N = 0`), as the tag will be silently truncated.
//!
//! # Terminology
//!
//! Throughout this crate's API and its documentation a certain terminology is
//! consistently used, which is summarized below:
//!
//! - record
//!
//! A heap allocated value which is managed by some reclamation scheme.
//!
//! - unlink
//!
//! The act removing the pointer to a *record* from shared memory through an
//! atomic operation such as *compare-and-swap*.
//!
//! - retire
//!
//! The act of marking an *unlinked* record as no longer in use and handing
//! off the responsibility for de-allocation to the reclamation scheme.
//!
//! - reclaim
//!
//! The act of dropping and de-allocating a *retired* record.
//! The reclamation scheme is responsible for guaranteeing that *retired*
//! records are kept alive (cached) **at least** until their respective *grace
//! periods* have expired.
#![cfg_attr(not(any(test, feature = "std")), no_std)]
#![warn(missing_docs)]
#[cfg(not(feature = "std"))]
extern crate alloc;
#[macro_use]
mod macros;
pub mod align;
pub mod leak;
pub mod prelude {
//! Useful and/or required types, discriminants and traits for the `reclaim`
//! crate.
pub use crate::pointer::{
Marked::{self, Null, Value},
MarkedNonNullable, MarkedPointer,
};
pub use crate::util::{UnwrapMutPtr, UnwrapPtr, UnwrapUnchecked};
pub use crate::GlobalReclaim;
pub use crate::Protect;
pub use crate::ProtectRegion;
pub use crate::Reclaim;
}
mod atomic;
mod internal;
mod owned;
mod pointer;
mod retired;
mod shared;
mod traits;
mod unlinked;
mod unprotected;
mod util;
#[cfg(feature = "std")]
use std::error::Error;
use core::fmt;
use core::marker::PhantomData;
use core::mem;
use core::ptr::NonNull;
use core::sync::atomic::Ordering;
// TODO: replace with const generics once available
pub use typenum;
use memoffset::offset_of;
use typenum::Unsigned;
pub use crate::atomic::{Atomic, CompareExchangeFailure};
pub use crate::pointer::{
AtomicMarkedPtr, InvalidNullError, Marked, MarkedNonNull, MarkedNonNullable, MarkedPointer,
MarkedPtr,
};
pub use crate::retired::Retired;
////////////////////////////////////////////////////////////////////////////////////////////////////
// GlobalReclaim (trait)
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A trait for retiring and reclaiming entries removed from concurrent
/// collections and data structures.
///
/// Implementing this trait requires first implementing the [`Reclaim`]
/// trait for the same type and is usually only possible in `std` environments
/// with access to thread local storage.
///
/// # Examples
///
/// Defining a concurrent data structure generic over the employed reclamation
/// scheme:
///
/// ```
/// use reclaim::typenum::U0;
/// use reclaim::GlobalReclaim;
///
/// type Atomic<T, R> = reclaim::Atomic<T, R, U0>;
///
/// pub struct Stack<T, R: GlobalReclaim> {
/// head: Atomic<Node<T, R>, R>,
/// }
///
/// struct Node<T, R: GlobalReclaim> {
/// elem: T,
/// next: Atomic<Node<T, R>, R>,
/// }
/// ```
pub unsafe trait GlobalReclaim
where
Self: Reclaim,
{
/// The type used for protecting concurrently shared references.
type Guard: Protect<Reclaimer = Self> + Default;
/// Creates a new [`Guard`][GlobalReclaim::Guard].
///
/// When `Self::Guard` implements [`ProtectRegion`], this operation
/// instantly establishes protection for loaded values.
/// Otherwise, the guard must first explicitly protect a specific shared
/// value.
fn guard() -> Self::Guard {
Self::Guard::default()
}
/// Attempts to reclaim some retired records.
///
/// When records are retired, they usually have to be stashed away for some
/// time, before they can be safely reclaimed.
/// This function initiates a manual collection attempt and tries to reclaim
/// some of these records.
/// Whether this affects all retired records or only records retired by the
/// current thread depends on the implementation.
/// Whether the reclaim attempt is bounded in some way or could potentially
/// reclaim all retired records is likewise implementation dependent.
fn try_reclaim();
/// Retires a record and caches it **at least** until it is safe to
/// deallocate it.
///
/// For further information, refer to the documentation of
/// [`retire_local`][`Reclaim::retire_local`].
///
/// # Safety
///
/// The same caveats as with [`retire_local`][`LocalReclaim::retire_local`]
/// apply.
///
/// # Examples
///
/// ```
/// use std::sync::atomic::Ordering;
///
/// use reclaim::leak::Leaking;
/// use reclaim::{GlobalReclaim, Owned};
///
/// type Atomic<T> = reclaim::leak::Atomic<T, reclaim::typenum::U0>;
///
/// let atomic = Atomic::new(String::from("owned string"));
/// if let Some(unlinked) = atomic.swap(Owned::none(), Ordering::SeqCst) {
/// unsafe { Leaking::retire(unlinked) };
/// }
/// ```
unsafe fn retire<T: 'static, N: Unsigned>(unlinked: Unlinked<T, Self, N>);
/// Retires a record and caches it **at least** until it is safe to
/// deallocate it.
///
/// For further information, refer to the documentation of
/// [`retire_local_unchecked`][`Reclaim::retire_local_unchecked`].
///
/// # Safety
///
/// The same caveats as with [`retire_local`][`Reclaim::retire_local`]
/// apply.
///
/// # Examples
///
/// It is usually safe to call `retire_unchecked` on types wrapped by
/// e.g. [`ManuallyDrop`][core::mem::ManuallyDrop].
///
/// ```
/// use std::mem::ManuallyDrop;
/// use std::sync::atomic::Ordering;
///
/// use reclaim::leak::Leaking;
/// use reclaim::{GlobalReclaim, Owned};
///
/// type Atomic<T> = reclaim::leak::Atomic<T, reclaim::typenum::U0>;
///
/// struct PrintOnDrop<'a> {
/// reference: &'a i32,
/// }
///
/// impl<'a> Drop for PrintOnDrop<'a> {
/// fn drop(&mut self) {
/// println!("dropping reference to {}", self.reference);
/// }
/// }
///
/// let drop = ManuallyDrop::new(PrintOnDrop {
/// reference: &1
/// });
///
/// let atomic = Atomic::new(drop);
///
/// if let Some(unlinked) = atomic.swap(Owned::none(), Ordering::SeqCst) {
/// unsafe { Leaking::retire_unchecked(unlinked) };
/// }
/// ```
unsafe fn retire_unchecked<T, N: Unsigned>(unlinked: Unlinked<T, Self, N>);
/// Retires a raw marked pointer to a record.
///
/// # Safety
///
/// The same caveats as with [`retire_local_raw`][`Reclaim::retire_local_raw`]
/// apply.
///
/// # Panics
///
/// In debug mode, this function panics if `ptr` is `null`.
unsafe fn retire_raw<T, N: Unsigned>(ptr: MarkedPtr<T, N>) {
debug_assert!(!ptr.is_null());
Self::retire_unchecked(Unlinked::from_marked_ptr(ptr));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Reclaim (trait)
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A trait, which constitutes the foundation for the [`GlobalReclaim`] trait.
///
/// This trait is specifically intended to be fully compatible with `#[no_std]`
/// environments.
/// This is expressed by the requirement to explicitly pass references to thread
/// local state or storage when calling functions that retire records.
///
/// If a reclamation scheme does not require or deliberately chooses to avoid
/// using thread local storage for the sake of simplicity or portability
/// (usually at the cost of performance), it is valid to implement `Self::Local`
/// as `()` and pass all retired records directly through to some global state.
/// Note, that this will generally require more and also more frequent
/// synchronization.
/// For cases in which `Local` is defined to be `()`, there exists a blanket
/// implementation of [`GlobalReclaim].
pub unsafe trait Reclaim
where
Self: Sized + 'static,
{
/// The type used for storing all relevant thread local state.
type Local: Sized;
/// Every record allocates this type alongside itself to store additional
/// reclamation scheme specific data.
/// When no such data is required, `()` is the recommended choice.
type RecordHeader: Default + Sync + Sized;
/// Retires a record and caches it **at least** until it is safe to
/// deallocate it.
///
/// How to determine that no other thread can possibly have any (protected)
/// reference to a record depends on the respective reclamation scheme.
///
/// # Safety
///
/// The caller has to guarantee that the record is **fully** unlinked from
/// any data structure it was previously inserted in:
/// There must be no way for another thread to acquire a *new* reference to
/// the given `unlinked` record.
///
/// While an [`Unlinked`] value can only safely be obtained by atomic
/// operations that do in fact remove a value from its place in memory (i.e.
/// *swap* or *compare-and-swap*), this is only the *necessary* condition
/// for safe reclamation, but not always *sufficient*.
/// When a unique address to heap allocated memory is inserted in more than
/// one element of a shared data structure, it is still possible for other
/// threads to access this address even if its unlinked from one spot.
///
/// This invariant also mandates, that correct synchronization of atomic
/// operations around calls to functions that retire records is ensured.
/// Consider the following (incorrect) example:
///
/// ```ignore
/// # use core::sync::atomic::Ordering::{Relaxed};
/// # use reclaim::Unlinked;
///
/// let g = Atomic::from(Owned::new(1));
///
/// // thread 1
/// let expected = g.load_unprotected(Relaxed); // reads &1
/// let unlinked = g
/// .compare_exchange(expected, Owned::null(), Relaxed, Relaxed)
/// .unwrap();
///
/// unsafe { unlinked.retire() };
///
/// // thread 2
/// if let Some(shared) = g.load(Relaxed, &mut guard) {
/// assert_eq!(*shared, &1); // !!! may read freed memory
/// }
/// ```
///
/// In this example, the invariant can not be guaranteed to be maintained,
/// due to the incorrect (relaxed) memory orderings.
/// Thread 1 can potentially unlink the shared value, retire and reclaim it,
/// without the `compare_exchange` operation ever becoming visible to
/// thread 2.
/// The thread could then proceed to load and read the previous
/// value instead of the inserted `null`, accessing freed memory.
unsafe fn retire_local<T: 'static, N: Unsigned>(
local: &Self::Local,
unlinked: Unlinked<T, Self, N>,
);
/// Retires a record and caches it **at least** until it is safe to
/// deallocate it.
///
/// How to determine that no other thread can possibly have any (protected)
/// reference to a record depends on the respective reclamation scheme.
///
/// # Safety
///
/// The same restrictions as with the [`retire_local`][Reclaim::retire_local]
/// function apply here as well.
///
/// In addition to these invariants, this method additionally requires the
/// caller to ensure any `Drop` implementation for `T` or any contained type
/// does not access any **non-static** references.
/// The `reclaim` interface makes no guarantees about the precise time a
/// retired record is actually reclaimed.
/// Hence, it is not possible to ensure any references stored within the
/// record have not become invalid at that point.
unsafe fn retire_local_unchecked<T, N: Unsigned>(
local: &Self::Local,
unlinked: Unlinked<T, Self, N>,
);
/// Retires a raw marked pointer to a record.
///
/// # Safety
///
/// The same restrictions as with [`retire_local_unchecked`][Reclaim::retire_local_unchecked]
/// apply.
/// Since this function accepts a raw pointer, no type level checks on the validity are possible
/// and are hence the responsibility of the caller.
///
/// # Panics
///
/// In debug mode, this function panics if `ptr` is `null`.
unsafe fn retire_local_raw<T, N: Unsigned>(local: &Self::Local, ptr: MarkedPtr<T, N>) {
debug_assert!(!ptr.is_null());
Self::retire_local_unchecked(local, Unlinked::from_marked_ptr(ptr));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Protect (trait)
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A trait for guard types that *protect* a specific value from reclamation
/// during the lifetime of the protecting guard.
///
/// # Examples
///
/// ```
/// use core::sync::atomic::Ordering::Relaxed;
///
/// use reclaim::typenum::U0;
/// use reclaim::prelude::*;
/// // `Leaking` implements both `Protect` and `ProtectRegion`
/// use reclaim::leak::Guard;
///
/// type Atomic<T> = reclaim::leak::Atomic<T, U0>;
///
/// let atomic = Atomic::new(1);
///
/// let mut guard = Guard::new();
/// let shared = atomic.load(Relaxed, &mut guard).unwrap();
/// assert_eq!(&*shared, &1);
/// ```
pub unsafe trait Protect
where
Self: Clone + Sized,
{
/// The reclamation scheme associated with this type of guard
type Reclaimer: Reclaim;
/// Converts the guard into a [`Guarded`] by fusing it with a value loaded
/// from `atomic`.
///
/// # Errors
///
/// If the value loaded from `atomic` is `null`, this method instead `self`
/// again, wrapped in an [`Err`].
#[inline]
fn try_fuse<T, N: Unsigned>(
mut self,
atomic: &Atomic<T, Self::Reclaimer, N>,
order: Ordering,
) -> Result<Guarded<T, Self, N>, Self> {
if let Marked::Value(shared) = self.protect(atomic, order) {
let ptr = Shared::into_marked_non_null(shared);
Ok(Guarded { guard: self, ptr })
} else {
Err(self)
}
}
/// Releases any current protection that may be provided by the guard.
///
/// By borrowing `self` mutably it is ensured that no loaded values
/// protected by this guard can be used after calling this method.
/// If `Self` additionally implements [`ProtectRegion`], this is a no-op
fn release(&mut self);
/// Atomically takes a snapshot of `atomic` and returns a protected
/// [`Shared`] reference wrapped in a [`Marked`] to it.
///
/// The loaded value is stored within `self`. If the value of `atomic` is
/// `null` or a pure tag (marked `null` pointer), no protection has to be
/// established. Any previously protected value will be overwritten and be
/// no longer protected, regardless of the loaded value.
///
/// # Panics
///
/// *May* panic if `order` is [`Release`][release] or [`AcqRel`][acq_rel].
///
/// [release]: core::sync::atomic::Ordering::Release
/// [acq_rel]: core::sync::atomic::Ordering::AcqRel
///
/// # Examples
///
/// Usually, this method will only be called indirectly by calling e.g.
/// [`load`][Atomic::load] with a mutable reference to the guard
/// implementing [`Protect`]
///
/// ```
/// use std::sync::atomic::Ordering;
///
/// use reclaim::leak::Guard;
/// use reclaim::Protect;
///
/// type Atomic<T> = reclaim::leak::Atomic<T, reclaim::typenum::U0>;
///
/// let atomic = Atomic::new(1);
///
/// let mut guard = Guard::new();
/// if let Some(shared) = atomic.load(Ordering::SeqCst, &mut guard) {
/// assert_eq!(*shared, 1);
/// }
/// ```
fn protect<T, N: Unsigned>(
&mut self,
atomic: &Atomic<T, Self::Reclaimer, N>,
order: Ordering,
) -> Marked<Shared<T, Self::Reclaimer, N>>;
/// Atomically takes a snapshot of `atomic` and returns a protected
/// [`Shared`] reference wrapped in a [`Marked`] to it, **if** the loaded
/// value is equal to `expected`.
///
/// A *successfully* loaded value is stored within `self`. If the value of
/// `atomic` is `null` or a pure tag (marked `null` pointer), no protection
/// has to be established. After a *successful* load, any previously
/// protected value will be overwritten and be no longer protected,
/// regardless of the loaded value. In case of a unsuccessful load, the
/// previously protected value does not change.
///
/// # Errors
///
/// This method returns an [`Err(NotEqualError)`][NotEqualError] result, if
/// the atomically loaded snapshot from `atomic` does not match the
/// `expected` value.
///
/// # Panics
///
/// *May* panic if `order` is [`Release`][release] or [`AcqRel`][acq_rel].
///
/// [release]: core::sync::atomic::Ordering::Release
/// [acq_rel]: core::sync::atomic::Ordering::AcqRel
fn protect_if_equal<T, N: Unsigned>(
&mut self,
atomic: &Atomic<T, Self::Reclaimer, N>,
expected: MarkedPtr<T, N>,
order: Ordering,
) -> AcquireResult<T, Self::Reclaimer, N>;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// ProtectRegion (trait)
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A trait for guard types that protect any values loaded during their
/// existence and lifetime.
///
/// # Examples
///
/// ```
/// use core::sync::atomic::Ordering::Relaxed;
///
/// use reclaim::typenum::U0;
/// use reclaim::prelude::*;
/// // `Leaking` implements both `Protect` and `ProtectRegion`
/// use reclaim::leak::Guard;
///
/// type Atomic<T> = reclaim::leak::Atomic<T, U0>;
///
/// let atomic = Atomic::new(1);
/// let other = Atomic::new(0);
///
/// let guard = Guard::new();
/// let shared1 = atomic.load(Relaxed, &guard).unwrap();
/// let shared0 = other.load(Relaxed, &guard).unwrap();
/// assert_eq!(&*shared1, &1);
/// assert_eq!(&*shared0, &0);
/// ```
pub unsafe trait ProtectRegion
where
Self: Protect,
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// AcquireResult
////////////////////////////////////////////////////////////////////////////////////////////////////
/// Result type for [`acquire_if_equal`][Protect::acquire_if_equal] operations.
pub type AcquireResult<'g, T, R, N> = Result<Marked<Shared<'g, T, R, N>>, NotEqualError>;
////////////////////////////////////////////////////////////////////////////////////////////////////
// NotEqualError
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A zero-size marker type that represents the failure state of an
/// [`acquire_if_equal`][Protect::acquire_if_equal] operation.
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub struct NotEqualError;
/********** impl Display **************************************************************************/
impl fmt::Display for NotEqualError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "acquired value does not match `expected`.")
}
}
/********** impl Error ****************************************************************************/
#[cfg(feature = "std")]
impl Error for NotEqualError {}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Record
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A record type that is associated with a specific reclamation scheme.
///
/// Whenever a new [`Owned`] or (non-null) [`Atomic`] is created, a value of
/// this type is allocated on the heap as a wrapper for the desired record.
/// The record and its header are never directly exposed to the data structure
/// using a given memory reclamation scheme and should only be accessed by the
/// reclamation scheme itself.
pub struct Record<T, R: Reclaim> {
/// The record's header
header: R::RecordHeader,
/// The record's wrapped (inner) element
elem: T,
}
/********** impl inherent *************************************************************************/
impl<T, R: Reclaim> Record<T, R> {
/// Creates a new record with the specified `elem` and a default header.
#[inline]
pub fn new(elem: T) -> Self {
Self { header: Default::default(), elem }
}
/// Creates a new record with the specified `elem` and `header`.
#[inline]
pub fn with_header(elem: T, header: R::RecordHeader) -> Self {
Self { header, elem }
}
/// Returns a reference to the record's header.
#[inline]
pub fn header(&self) -> &R::RecordHeader {
&self.header
}
/// Returns a reference to the record's element.
#[inline]
pub fn elem(&self) -> &T {
&self.elem
}
/// Calculates the address of the [`Record`] for the given pointer to a
/// wrapped non-nullable `elem` and returns the resulting pointer.
///
/// # Safety
///
/// The `elem` pointer must be a valid pointer to an instance of `T` that
/// was constructed as part of a [`Record`]. Otherwise, the pointer
/// arithmetic used to determine the address will result in a pointer to
/// unrelated memory, which is likely to lead to undefined behaviour.
#[inline]
pub unsafe fn from_raw_non_null(elem: NonNull<T>) -> NonNull<Self> {
Self::from_raw(elem.as_ptr())
}
/// Calculates the address of the [`Record`] for the given pointer to a
/// wrapped `elem` and returns the resulting pointer.
///
/// # Safety
///
/// The `elem` pointer must be a valid pointer to an instance of `T` that
/// was constructed as part of a [`Record`]. Otherwise, the pointer
/// arithmetic used to determine the address will result in a pointer to
/// unrelated memory, which is likely to lead to undefined behaviour.
#[inline]
pub unsafe fn from_raw(elem: *mut T) -> NonNull<Self> {
let addr = (elem as usize) - Self::offset_elem();
NonNull::new_unchecked(addr as *mut _)
}
/// Returns a reference to the header for the record at the pointed-to
/// location of the pointer `elem`.
///
/// # Safety
///
/// The pointer `elem` must be a valid pointer to an instance of `T` that
/// was allocated as part of a `Record`.
/// Otherwise, the pointer arithmetic used to calculate the header's address
/// will be incorrect and lead to undefined behavior.
#[inline]
pub unsafe fn header_from_raw<'a>(elem: *mut T) -> &'a R::RecordHeader {
let header = (elem as usize) - Self::offset_elem() + Self::offset_header();
&*(header as *mut _)
}
/// Returns a reference to the header for the record at the pointed-to
/// location of the non-nullable pointer `elem`.
///
/// # Safety
///
/// The pointer `elem` must be a valid pointer to an instance of `T` that
/// was allocated as part of a `Record`.
/// Otherwise, the pointer arithmetic used to calculate the header's address
/// will be incorrect and lead to undefined behavior.
#[inline]
pub unsafe fn header_from_raw_non_null<'a>(elem: NonNull<T>) -> &'a R::RecordHeader {
let header = (elem.as_ptr() as usize) - Self::offset_elem() + Self::offset_header();
&*(header as *mut _)
}
/// Returns the offset in bytes from the address of a record to its header
/// field.
#[inline]
pub fn offset_header() -> usize {
// FIXME: the offset_of! macro is unsound, this allows at least avoiding using it
// in many cases until a better solution becomes available
// https://internals.rust-lang.org/t/pre-rfc-add-a-new-offset-of-macro-to-core-mem/9273
if mem::size_of::<R::RecordHeader>() == 0 {
0
} else {
offset_of!(Self, header)
}
}
/// Returns the offset in bytes from the address of a record to its element
/// field.
#[inline]
pub fn offset_elem() -> usize {
// FIXME: the offset_of! macro is currently, this allows at least avoiding using it
// in many cases until a better solution becomes available
// https://internals.rust-lang.org/t/pre-rfc-add-a-new-offset-of-macro-to-core-mem/9273
if mem::size_of::<R::RecordHeader>() == 0 {
0
} else {
offset_of!(Self, elem)
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Guarded
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A guard type fused with a protected value.
#[derive(Debug)]
pub struct Guarded<T, G, N: Unsigned> {
guard: G,
ptr: MarkedNonNull<T, N>,
}
/********** impl inherent *************************************************************************/
impl<T, G: Protect, N: Unsigned> Guarded<T, G, N> {
/// Returns a [`Shared`] reference borrowed from the [`Guarded`].
#[inline]
pub fn shared(&self) -> Shared<T, G::Reclaimer, N> {
Shared { inner: self.ptr, _marker: PhantomData }
}
/// Converts the [`Guarded`] into the internally stored guard.
///
/// If `G` does not implement [`ProtectRegion`], the returned guard is
/// guaranteed to be [`released`][Protect::release] before being returned.
#[inline]
pub fn into_guard(self) -> G {
let mut guard = self.guard;
guard.release();
guard
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Owned
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A pointer type for heap allocated values similar to `Box`.
///
/// `Owned` values function like marked pointers and are also guaranteed to
/// allocate the appropriate [`RecordHeader`][Reclaim::RecordHeader] type
/// for its generic [`Reclaim`] parameter alongside their actual content.
#[derive(Eq, Ord, PartialEq, PartialOrd)]
pub struct Owned<T, R: Reclaim, N: Unsigned> {
inner: MarkedNonNull<T, N>,
_marker: PhantomData<(T, R)>,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Shared (impl in shared.rs)
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A shared reference to a value that is actively protected from reclamation by
/// other threads.
///
/// `Shared` values have similar semantics to shared references (`&'g T`), i.e.
/// they can be trivially copied, cloned and (safely) de-referenced.
/// However, they do retain potential mark bits of the atomic value from which
/// they were originally read.
/// They are also usually borrowed from guard values implementing the
/// [`Protect`] trait.
pub struct Shared<'g, T, R, N> {
inner: MarkedNonNull<T, N>,
_marker: PhantomData<(&'g T, R)>,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Unlinked (impl in unlinked.rs)
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A reference to a value that has been removed from its previous location in
/// memory and is hence no longer reachable by other threads.
///
/// `Unlinked` values are the result of (successful) atomic *swap* or
/// *compare-and-swap* operations on [`Atomic`] values.
/// They are move-only types, but they don't have full ownership semantics,
/// either.
/// Dropping an `Unlinked` value without explicitly retiring it almost certainly
/// results in a memory leak.
///
/// The safety invariants around retiring `Unlinked` references are explained
/// in detail in the documentation for [`retire_local`][Reclaim::retire_local].
#[derive(Eq, Ord, PartialEq, PartialOrd)]
#[must_use = "unlinked values are meant to be retired, otherwise a memory leak is highly likely"]
pub struct Unlinked<T, R, N> {
inner: MarkedNonNull<T, N>,
_marker: PhantomData<(T, R)>,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Unprotected (impl in unprotected.rs)
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A reference to a value loaded from an [`Atomic`] that is not actively
/// protected from reclamation.
///
/// `Unprotected` values can not be safely de-referenced under usual
/// circumstances (i.e. other threads can retire and reclaim unlinked records).
/// They do, however, have stronger guarantees than raw (marked) pointers:
/// Since are loaded from [`Atomic`] values they must (at least at one point)
/// have been *valid* references.
#[derive(Eq, Ord, PartialEq, PartialOrd)]
pub struct Unprotected<T, R, N> {
inner: MarkedNonNull<T, N>,
_marker: PhantomData<R>,
}
|
use anyhow::Context;
use pathfinder_common::{BlockHash, BlockHeader, BlockNumber, StarknetVersion};
use crate::{prelude::*, BlockId};
pub(super) fn insert_block_header(
tx: &Transaction<'_>,
header: &BlockHeader,
) -> anyhow::Result<()> {
// Intern the starknet version
let version_id = intern_starknet_version(tx, &header.starknet_version)
.context("Interning starknet version")?;
// Insert the header
tx.inner().execute(
r"INSERT INTO block_headers
( number, hash, storage_commitment, timestamp, gas_price, sequencer_address, version_id, transaction_commitment, event_commitment, state_commitment, class_commitment, transaction_count, event_count)
VALUES (:number, :hash, :storage_commitment, :timestamp, :gas_price, :sequencer_address, :version_id, :transaction_commitment, :event_commitment, :state_commitment, :class_commitment, :transaction_count, :event_count)",
named_params! {
":number": &header.number,
":hash": &header.hash,
":storage_commitment": &header.storage_commitment,
":timestamp": &header.timestamp,
":gas_price": &header.gas_price.to_be_bytes().as_slice(),
":sequencer_address": &header.sequencer_address,
":version_id": &version_id,
":transaction_commitment": &header.transaction_commitment,
":event_commitment": &header.event_commitment,
":class_commitment": &header.class_commitment,
":transaction_count": &header.transaction_count.try_into_sql_int()?,
":event_count": &header.event_count.try_into_sql_int()?,
":state_commitment": &header.state_commitment,
},
).context("Inserting block header")?;
// This must occur after the header is inserted as this table references the header table.
tx.inner()
.execute(
"INSERT INTO canonical_blocks(number, hash) values(?,?)",
params![&header.number, &header.hash],
)
.context("Inserting into canonical_blocks table")?;
Ok(())
}
fn intern_starknet_version(tx: &Transaction<'_>, version: &StarknetVersion) -> anyhow::Result<i64> {
let id: Option<i64> = tx
.inner()
.query_row(
"SELECT id FROM starknet_versions WHERE version = ?",
params![version],
|r| Ok(r.get_unwrap(0)),
)
.optional()
.context("Querying for an existing starknet_version")?;
let id = if let Some(id) = id {
id
} else {
// sqlite "autoincrement" for integer primary keys works like this: we leave it out of
// the insert, even though it's not null, it will get max(id)+1 assigned, which we can
// read back with last_insert_rowid
let rows = tx
.inner()
.execute(
"INSERT INTO starknet_versions(version) VALUES (?)",
params![version],
)
.context("Inserting unique starknet_version")?;
anyhow::ensure!(rows == 1, "Unexpected number of rows inserted: {rows}");
tx.inner().last_insert_rowid()
};
Ok(id)
}
pub(super) fn purge_block(tx: &Transaction<'_>, block: BlockNumber) -> anyhow::Result<()> {
// This table does not have an ON DELETE clause, so we do it manually.
// TODO: migration to add ON DELETE.
tx.inner()
.execute(
"UPDATE class_definitions SET block_number = NULL WHERE block_number = ?",
params![&block],
)
.context("Unsetting class definitions block number")?;
tx.inner()
.execute(
r"DELETE FROM starknet_transactions WHERE block_hash = (
SELECT hash FROM canonical_blocks WHERE number = ?
)",
params![&block],
)
.context("Deleting transactions")?;
tx.inner()
.execute(
"DELETE FROM canonical_blocks WHERE number = ?",
params![&block],
)
.context("Deleting block from canonical_blocks table")?;
tx.inner()
.execute(
"DELETE FROM block_headers WHERE number = ?",
params![&block],
)
.context("Deleting block from block_headers table")?;
Ok(())
}
pub(super) fn block_id(
tx: &Transaction<'_>,
block: BlockId,
) -> anyhow::Result<Option<(BlockNumber, BlockHash)>> {
match block {
BlockId::Latest => tx.inner().query_row(
"SELECT number, hash FROM canonical_blocks ORDER BY number DESC LIMIT 1",
[],
|row| {
let number = row.get_block_number(0)?;
let hash = row.get_block_hash(1)?;
Ok((number, hash))
},
),
BlockId::Number(number) => tx.inner().query_row(
"SELECT hash FROM canonical_blocks WHERE number = ?",
params![&number],
|row| {
let hash = row.get_block_hash(0)?;
Ok((number, hash))
},
),
BlockId::Hash(hash) => tx.inner().query_row(
"SELECT number FROM canonical_blocks WHERE hash = ?",
params![&hash],
|row| {
let number = row.get_block_number(0)?;
Ok((number, hash))
},
),
}
.optional()
.map_err(|e| e.into())
}
pub(super) fn block_exists(tx: &Transaction<'_>, block: BlockId) -> anyhow::Result<bool> {
match block {
BlockId::Latest => {
tx.inner()
.query_row("SELECT EXISTS(SELECT 1 FROM canonical_blocks)", [], |row| {
row.get(0)
})
}
BlockId::Number(number) => tx.inner().query_row(
"SELECT EXISTS(SELECT 1 FROM canonical_blocks WHERE number = ?)",
params![&number],
|row| row.get(0),
),
BlockId::Hash(hash) => tx.inner().query_row(
"SELECT EXISTS(SELECT 1 FROM canonical_blocks WHERE hash = ?)",
params![&hash],
|row| row.get(0),
),
}
.map_err(|e| e.into())
}
pub(super) fn block_header(
tx: &Transaction<'_>,
block: BlockId,
) -> anyhow::Result<Option<BlockHeader>> {
// TODO: is LEFT JOIN reasonable? It's required because version ID can be null for non-existent versions.
const BASE_SQL: &str = "SELECT * FROM block_headers LEFT JOIN starknet_versions ON block_headers.version_id = starknet_versions.id";
let sql = match block {
BlockId::Latest => format!("{BASE_SQL} ORDER BY number DESC LIMIT 1"),
BlockId::Number(_) => format!("{BASE_SQL} WHERE number = ?"),
BlockId::Hash(_) => format!("{BASE_SQL} WHERE hash = ?"),
};
let parse_row = |row: &rusqlite::Row<'_>| {
let number = row.get_block_number("number")?;
let hash = row.get_block_hash("hash")?;
let storage_commitment = row.get_storage_commitment("storage_commitment")?;
let timestamp = row.get_timestamp("timestamp")?;
let gas_price = row.get_gas_price("gas_price")?;
let sequencer_address = row.get_sequencer_address("sequencer_address")?;
let transaction_commitment = row.get_transaction_commitment("transaction_commitment")?;
let event_commitment = row.get_event_commitment("event_commitment")?;
let class_commitment = row.get_class_commitment("class_commitment")?;
let starknet_version = row.get_starknet_version("version")?;
let event_count: usize = row.get("event_count")?;
let transaction_count: usize = row.get("transaction_count")?;
let state_commitment = row.get_state_commitment("state_commitment")?;
let header = BlockHeader {
hash,
number,
timestamp,
gas_price,
sequencer_address,
class_commitment,
event_commitment,
state_commitment,
storage_commitment,
transaction_commitment,
starknet_version,
transaction_count,
event_count,
// TODO: store block hash in-line.
// This gets filled in by a separate query, but really should get stored as a column in
// order to support truncated history.
parent_hash: BlockHash::default(),
};
Ok(header)
};
let header = match block {
BlockId::Latest => tx.inner().query_row(&sql, [], parse_row),
BlockId::Number(number) => tx.inner().query_row(&sql, params![&number], parse_row),
BlockId::Hash(hash) => tx.inner().query_row(&sql, params![&hash], parse_row),
}
.optional()
.context("Querying for block header")?;
let Some(mut header) = header else {
return Ok(None);
};
// Fill in parent hash (unless we are at genesis in which case the current ZERO is correct).
if header.number != BlockNumber::GENESIS {
let parent_hash = tx
.inner()
.query_row(
"SELECT hash FROM block_headers WHERE number = ?",
params![&(header.number - 1)],
|row| row.get_block_hash(0),
)
.context("Querying parent hash")?;
header.parent_hash = parent_hash;
}
Ok(Some(header))
}
pub(super) fn block_is_l1_accepted(tx: &Transaction<'_>, block: BlockId) -> anyhow::Result<bool> {
let Some(l1_l2) = tx.l1_l2_pointer().context("Querying L1-L2 pointer")? else {
return Ok(false);
};
let Some((block_number, _)) = tx.block_id(block).context("Fetching block number")? else {
return Ok(false);
};
Ok(block_number <= l1_l2)
}
#[cfg(test)]
mod tests {
use pathfinder_common::macro_prelude::*;
use pathfinder_common::{
BlockTimestamp, ClassCommitment, ClassHash, EventCommitment, GasPrice, StateCommitment,
StateUpdate, TransactionCommitment,
};
use super::*;
use crate::Connection;
// Create test database filled with block headers.
fn setup() -> (Connection, Vec<BlockHeader>) {
let storage = crate::Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
// This intentionally does not use the builder so that we don't forget to test
// any new fields that get added.
//
// Set unique values so we can be sure we are (de)serializing correctly.
let storage_commitment = storage_commitment_bytes!(b"storage commitment genesis");
let class_commitment = class_commitment_bytes!(b"class commitment genesis");
let genesis = BlockHeader {
hash: block_hash_bytes!(b"genesis hash"),
parent_hash: BlockHash::ZERO,
number: BlockNumber::GENESIS,
timestamp: BlockTimestamp::new_or_panic(10),
gas_price: GasPrice(32),
sequencer_address: sequencer_address_bytes!(b"sequencer address genesis"),
starknet_version: StarknetVersion::default(),
class_commitment,
event_commitment: event_commitment_bytes!(b"event commitment genesis"),
state_commitment: StateCommitment::calculate(storage_commitment, class_commitment),
storage_commitment,
transaction_commitment: transaction_commitment_bytes!(b"tx commitment genesis"),
transaction_count: 37,
event_count: 40,
};
let header1 = genesis
.child_builder()
.with_timestamp(BlockTimestamp::new_or_panic(12))
.with_gas_price(GasPrice(34))
.with_sequencer_address(sequencer_address_bytes!(b"sequencer address 1"))
.with_event_commitment(event_commitment_bytes!(b"event commitment 1"))
.with_class_commitment(class_commitment_bytes!(b"class commitment 1"))
.with_storage_commitment(storage_commitment_bytes!(b"storage commitment 1"))
.with_calculated_state_commitment()
.with_transaction_commitment(transaction_commitment_bytes!(b"tx commitment 1"))
.finalize_with_hash(block_hash_bytes!(b"block 1 hash"));
let header2 = header1
.child_builder()
.with_gas_price(GasPrice(38))
.with_timestamp(BlockTimestamp::new_or_panic(15))
.with_sequencer_address(sequencer_address_bytes!(b"sequencer address 2"))
.with_event_commitment(event_commitment_bytes!(b"event commitment 2"))
.with_class_commitment(class_commitment_bytes!(b"class commitment 2"))
.with_storage_commitment(storage_commitment_bytes!(b"storage commitment 2"))
.with_calculated_state_commitment()
.with_transaction_commitment(transaction_commitment_bytes!(b"tx commitment 2"))
.finalize_with_hash(block_hash_bytes!(b"block 2 hash"));
let headers = vec![genesis, header1, header2];
for header in &headers {
tx.insert_block_header(header).unwrap();
}
tx.commit().unwrap();
(connection, headers)
}
#[test]
fn get_latest() {
let (mut connection, headers) = setup();
let tx = connection.transaction().unwrap();
let result = tx.block_header(BlockId::Latest).unwrap().unwrap();
let expected = headers.last().unwrap();
assert_eq!(&result, expected);
}
#[test]
fn get_by_number() {
let (mut connection, headers) = setup();
let tx = connection.transaction().unwrap();
for header in &headers {
let result = tx.block_header(header.number.into()).unwrap().unwrap();
assert_eq!(&result, header);
}
let past_head = headers.last().unwrap().number + 1;
let result = tx.block_header(past_head.into()).unwrap();
assert_eq!(result, None);
}
#[test]
fn get_by_hash() {
let (mut connection, headers) = setup();
let tx = connection.transaction().unwrap();
for header in &headers {
let result = tx.block_header(header.hash.into()).unwrap().unwrap();
assert_eq!(&result, header);
}
let invalid = block_hash_bytes!(b"invalid block hash");
let result = tx.block_header(invalid.into()).unwrap();
assert_eq!(result, None);
}
#[test]
fn get_works_with_null_fields() {
// The migration introducing transaction, event and class commitments allowed them
// to be NULL (and defaulted to NULL). This test ensures that these are correctly handled
// and defaulted to ZERO.
//
// Starknet version was also allowed to be null which means that version_id can be null.
// This should default to an empty version string now.
let (mut connection, headers) = setup();
let tx = connection.transaction().unwrap();
let target = headers.last().unwrap();
// Overwrite the commitment fields to NULL.
tx.inner().execute(
r"UPDATE block_headers
SET transaction_commitment=NULL, event_commitment=NULL, class_commitment=NULL, version_id=NULL
WHERE number=?",
params![&target.number],
)
.unwrap();
let mut expected = target.clone();
expected.starknet_version = StarknetVersion::default();
expected.transaction_commitment = TransactionCommitment::ZERO;
expected.event_commitment = EventCommitment::ZERO;
expected.class_commitment = ClassCommitment::ZERO;
let result = tx.block_header(target.number.into()).unwrap().unwrap();
assert_eq!(result, expected);
}
#[test]
fn purge_block() {
let (mut connection, headers) = setup();
let tx = connection.transaction().unwrap();
let latest = headers.last().unwrap();
// Add a class to test that purging a block unsets its block number;
let cairo_hash = class_hash!("0x1234");
tx.insert_cairo_class(cairo_hash, &[]).unwrap();
tx.insert_state_update(
latest.number,
&StateUpdate::default().with_declared_cairo_class(cairo_hash),
)
.unwrap();
tx.purge_block(latest.number).unwrap();
let exists = tx.block_exists(latest.number.into()).unwrap();
assert!(!exists);
let class_exists = tx
.class_definition_at(latest.number.into(), ClassHash(cairo_hash.0))
.unwrap();
assert_eq!(class_exists, None);
}
#[test]
fn block_id() {
let (mut connection, headers) = setup();
let tx = connection.transaction().unwrap();
let target = headers.last().unwrap();
let expected = Some((target.number, target.hash));
let by_number = tx.block_id(target.number.into()).unwrap();
assert_eq!(by_number, expected);
let by_hash = tx.block_id(target.hash.into()).unwrap();
assert_eq!(by_hash, expected);
}
#[test]
fn block_is_l1_accepted() {
let (mut connection, headers) = setup();
let tx = connection.transaction().unwrap();
// Mark the genesis header as L1 accepted.
tx.update_l1_l2_pointer(Some(headers[0].number)).unwrap();
let l1_by_hash = tx.block_is_l1_accepted(headers[0].hash.into()).unwrap();
assert!(l1_by_hash);
let l1_by_number = tx.block_is_l1_accepted(headers[0].number.into()).unwrap();
assert!(l1_by_number);
// The second block will therefore be L2 accepted.
let l2_by_hash = tx.block_is_l1_accepted(headers[1].hash.into()).unwrap();
assert!(!l2_by_hash);
let l2_by_number = tx.block_is_l1_accepted(headers[1].number.into()).unwrap();
assert!(!l2_by_number);
}
}
|
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let input = 7689;
let mut fuel_cells = [[0i32; 300]; 300];
for y in 0..fuel_cells.len() {
let row = fuel_cells[y];
let y_coord = y + 1;
for x in 0..row.len() {
let x_coord = x + 1;
let rack_id = x_coord + 10;
let mut power_level = (rack_id * y_coord) as i32;
power_level += input as i32;
power_level *= rack_id as i32;
power_level = (power_level / 100) % 10;
power_level -= 5;
fuel_cells[y][x] = power_level;
}
}
let MaxPower { x, y, .. } = get_max_power(&fuel_cells, 3);
println!("part 1: {},{}", x, y);
let mut square = 1;
let mut max_power = get_max_power(&fuel_cells, square);
for i in 2..300 {
let mp = get_max_power(&fuel_cells, i);
if mp.power > max_power.power {
max_power = mp;
square = i;
}
}
println!("part 2: {},{},{}", max_power.x, max_power.y, square);
Ok(())
}
struct MaxPower {
x: usize,
y: usize,
power: i32,
}
fn get_max_power(fuel_cells: &[[i32; 300]], square_size: usize) -> MaxPower {
assert!(square_size >= 1);
assert!(square_size < 300);
let mut power = 0;
let mut top_left = (0, 0);
for y in 0..fuel_cells.len() - square_size - 1 {
let row = fuel_cells[y];
for x in 0..row.len() - square_size - 1 {
let mut sum = 0;
for y in y..y + square_size {
for x in x..x + square_size {
sum += fuel_cells[y][x];
}
}
if sum > power {
power = sum;
top_left = (x + 1, y + 1);
}
}
}
let (x, y) = top_left;
MaxPower { x, y, power }
}
|
use influxdb_iox_client::connection::Connection;
use influxdb_iox_client::namespace::generated_types::LimitUpdate;
use crate::commands::namespace::Result;
#[derive(Debug, clap::Parser)]
pub struct Config {
/// The namespace to update a service protection limit for
#[clap(action)]
namespace: String,
#[command(flatten)]
args: Args,
}
#[derive(Debug, clap::Args)]
#[clap(group(
// This arg group "limit" links the members of the below struct
// named "max_tables" and "max_columns_per_table" together as
// mutually exclusive flags. As we specify all flags & commands
// using clap-derive rather than the imperative builder, v3 only
// properly supports this kind of behaviour in a macro code block.
// NOTE: It takes the variable names and not the flag long names.
clap::ArgGroup::new("limit")
.required(true)
.args(&["max_tables", "max_columns_per_table"])
))]
pub struct Args {
/// The maximum number of tables to allow for this namespace
#[clap(action, long = "max-tables", short = 't', group = "limit")]
max_tables: Option<i32>,
/// The maximum number of columns to allow per table for this namespace
#[clap(action, long = "max-columns-per-table", short = 'c', group = "limit")]
max_columns_per_table: Option<i32>,
}
impl From<Args> for LimitUpdate {
fn from(args: Args) -> Self {
let Args {
max_tables,
max_columns_per_table,
} = args;
if let Some(n) = max_tables {
return Self::MaxTables(n);
}
if let Some(n) = max_columns_per_table {
return Self::MaxColumnsPerTable(n);
}
unreachable!();
}
}
pub async fn command(connection: Connection, config: Config) -> Result<()> {
let mut client = influxdb_iox_client::namespace::Client::new(connection);
let namespace = client
.update_namespace_service_protection_limit(
&config.namespace,
LimitUpdate::from(config.args),
)
.await?;
println!("{}", serde_json::to_string_pretty(&namespace)?);
println!(
r"
NOTE: This change will NOT take effect until all router instances have been restarted!"
);
Ok(())
}
|
// xfail-stage00
obj foo(@mutable int x) {
drop {
log "running dtor";
*x = ((*x) + 1);
}
}
fn main() {
auto mbox = @mutable 10;
{
auto x = foo(mbox);
}
check ((*mbox) == 11);
} |
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkAccelerationStructureMemoryRequirementsInfoNV {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub r#type: VkAccelerationStructureMemoryRequirementsTypeNV,
pub accelerationStructure: VkAccelerationStructureNV,
}
impl VkAccelerationStructureMemoryRequirementsInfoNV {
pub fn new(
r#type: VkAccelerationStructureMemoryRequirementsTypeNV,
acceleration_structure: VkAccelerationStructureNV,
) -> Self {
VkAccelerationStructureMemoryRequirementsInfoNV {
sType: VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_INFO_NV,
pNext: ptr::null(),
r#type,
accelerationStructure: acceleration_structure,
}
}
}
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags:-Zborrowck=mir -Zverbose
#![allow(warnings)]
trait Anything { }
impl<T> Anything for T { }
fn no_region<'a, T>(mut x: T) -> Box<dyn Anything + 'a>
where
T: Iterator,
{
Box::new(x.next())
//~^ WARNING not reporting region error due to nll
//~| the associated type `<T as std::iter::Iterator>::Item` may not live long enough
}
fn correct_region<'a, T>(mut x: T) -> Box<dyn Anything + 'a>
where
T: 'a + Iterator,
{
Box::new(x.next())
}
fn wrong_region<'a, 'b, T>(mut x: T) -> Box<dyn Anything + 'a>
where
T: 'b + Iterator,
{
Box::new(x.next())
//~^ WARNING not reporting region error due to nll
//~| the associated type `<T as std::iter::Iterator>::Item` may not live long enough
}
fn outlives_region<'a, 'b, T>(mut x: T) -> Box<dyn Anything + 'a>
where
T: 'b + Iterator,
'b: 'a,
{
Box::new(x.next())
}
fn main() {}
|
use std::mem;
use std::num::Int;
/// constant-time compare function.
/// `a` and `b` may be SECRET, but the length is known.
/// precondition: `a.len() == b.len()`
pub fn crypto_compare(a: &[u8], b: &[u8]) -> bool {
debug_assert_eq!(a.len(), b.len());
let mut diff = 0u8;
for i in (0..a.len()) {
diff |= a[i] ^ b[i];
}
diff = diff | (diff >> 4);
diff = diff | (diff >> 2);
diff = diff | (diff >> 1);
diff = diff & 1;
return diff == 0;
}
pub fn u64_be_array(x: u64) -> [u8; 8] {
unsafe { mem::transmute(x.to_be()) }
}
pub fn u64_le_array(x: u64) -> [u8; 8] {
unsafe { mem::transmute(x.to_le()) }
}
|
use crate::{
chromset::LexicalChromRef,
properties::{Parsable, Serializable, WithName, WithRegionCore, WithScore, WithStrand},
};
use crate::{ChromName, ChromSetHandle, WithChromSet};
use std::io::{Result, Write};
#[derive(Clone, Copy, PartialEq)]
pub struct Bed3<T: ChromName = LexicalChromRef> {
pub begin: u32,
pub end: u32,
pub chrom: T,
}
impl<T: ChromName> Bed3<T> {
pub fn with_chrom_list<H: ChromSetHandle>(self, chrom_list: &mut H) -> Bed3<H::RefType> {
let chrom = chrom_list.query_or_insert(self.chrom.to_string().as_ref());
Bed3 {
begin: self.begin,
end: self.end,
chrom,
}
}
}
impl<T: ChromName, H: ChromSetHandle> WithChromSet<H> for Bed3<T> {
type Result = Bed3<H::RefType>;
fn with_chrom_set(self, handle: &mut H) -> Self::Result {
self.with_chrom_list(handle)
}
}
impl<'a> Parsable<'a> for Bed3<&'a str> {
fn parse(s: &'a str) -> Option<(Self, usize)> {
let mut bytes = s.as_bytes();
if bytes.last() == Some(&b'\n') {
bytes = &bytes[..bytes.len() - 1];
}
let mut token_pos_iter = memchr::Memchr::new(b'\t', bytes);
let end_1 = token_pos_iter.next()?;
let end_2 = token_pos_iter.next()?;
let end_3 = token_pos_iter.next().unwrap_or(bytes.len());
let chrom = &s[..end_1];
Some((
Self {
chrom,
begin: s[end_1 + 1..end_2].parse().ok()?,
end: s[end_2 + 1..end_3].parse().ok()?,
},
end_3,
))
}
}
impl<C: ChromName + Clone> Bed3<C> {
pub fn new<T: WithRegionCore<C>>(region: T) -> Self {
Self {
begin: region.begin(),
end: region.end(),
chrom: region.chrom().clone(),
}
}
}
impl<T: ChromName> Serializable for Bed3<T> {
fn dump<W: Write>(&self, mut fp: W) -> Result<()> {
self.chrom().write(&mut fp)?;
fp.write(b"\t")?;
crate::ioutils::write_number(&mut fp, self.begin() as i32)?;
fp.write(b"\t")?;
crate::ioutils::write_number(&mut fp, self.end() as i32).map(|_| ())
}
}
impl<T: ChromName> WithRegionCore<T> for Bed3<T> {
fn begin(&self) -> u32 {
self.begin
}
fn end(&self) -> u32 {
self.end
}
fn chrom(&self) -> &T {
&self.chrom
}
}
impl<T: ChromName> WithName for Bed3<T> {
fn name(&self) -> &str {
"."
}
}
impl<T: ChromName> WithScore<i32> for Bed3<T> {}
impl<T: ChromName> WithStrand for Bed3<T> {}
|
extern crate data_encoding;
use std::env;
use std::io::{self, Read};
use data_encoding::hex;
fn decrypt(e_msg: &[u8], key: &str) -> String {
String::from_utf8(e_msg.iter().cloned().zip(key.bytes().cycle()).map(|(msg_byte, key_byte)| msg_byte ^ key_byte).collect()).unwrap()
}
fn main() {
if let Some(key) = env::args().nth(1) {
let mut stdin = io::stdin();
let mut buffer = String::new();
stdin.read_to_string(&mut buffer).unwrap();
let e_msg = hex::decode(buffer.trim().as_ref()).unwrap();
let decrypted_string = decrypt(&e_msg, &key);
print!("{}", decrypted_string);
} else {
println!("Give key pls.");
}
}
|
pub mod handy_haversacks_part_1;
pub mod handy_haversacks_part_2; |
use std::iter;
use radix;
use rand::{distributions::Alphanumeric, prelude::thread_rng, Rng};
pub fn create_slug_from_id(id: i32) -> String {
let id = format!("{}", id);
let r = radix::RadixNum::from_str(&id, 10).unwrap();
let r = r.with_radix(36).unwrap();
let mut slug = r.as_str().to_string();
if 6i32 - slug.len() as i32 > 0 {
let len = 6 - slug.len();
let mut rng = thread_rng();
slug = format!(
"{}{}",
slug,
iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.take(len)
.collect::<String>()
);
}
slug.to_uppercase()
}
#[cfg(test)]
mod tests {
use super::create_slug_from_id;
#[test]
fn returns_length_of_atleast_six() {
let slug = create_slug_from_id(10);
assert_eq!(slug.chars().next().unwrap(), 'A');
assert_eq!(slug.len(), 6);
}
#[test]
fn returns_full_string_if_six_length() {
let slug = create_slug_from_id(439483745);
assert_eq!(slug, "79NNTT");
}
}
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unions_with_drop_fields)]
// Drop works for union itself.
#![feature(untagged_unions)]
struct S;
union U {
a: S
}
impl Drop for S {
fn drop(&mut self) {
unsafe { CHECK += 10; }
}
}
impl Drop for U {
fn drop(&mut self) {
unsafe { CHECK += 1; }
}
}
static mut CHECK: u8 = 0;
fn main() {
unsafe {
let mut u = U { a: S };
assert_eq!(CHECK, 0);
u = U { a: S };
assert_eq!(CHECK, 1); // union itself is assigned, union is dropped, field is not dropped
u.a = S;
assert_eq!(CHECK, 11); // union field is assigned, field is dropped
}
}
|
// pub fn color_vec(colors: Vec<[u8; 3]>, intensity: f64) -> Vec<[u8; 3]> {
// let mut rendered_color: Vec<[u8; 3]> = Vec::new();
// for color in colors {
// rendered_color.push([
// (intensity * f64::from(color[0])) as u8,
// (intensity * f64::from(color[1])) as u8,
// (intensity * f64::from(color[2])) as u8,
// ]);
// }
// rendered_color
// }
pub fn color(color: [u8; 3], intensity: f64) -> [u8; 3] {
[
(intensity * f64::from(color[0])) as u8,
(intensity * f64::from(color[1])) as u8,
(intensity * f64::from(color[2])) as u8,
]
}
|
use std::{fmt, vec};
use indexmap::IndexMap;
use serde::{
de::{
self, Deserialize, DeserializeOwned, DeserializeSeed, EnumAccess, Error as DeError,
IntoDeserializer, MapAccess, SeqAccess, Unexpected, VariantAccess, Visitor,
},
forward_to_deserialize_any,
};
use crate::{ConstValue, Name};
/// This type represents errors that can occur when deserializing.
#[derive(Debug)]
pub struct DeserializerError(String);
impl de::Error for DeserializerError {
#[inline]
fn custom<T: fmt::Display>(msg: T) -> Self {
DeserializerError(msg.to_string())
}
}
impl std::error::Error for DeserializerError {
#[inline]
fn description(&self) -> &str {
"Value deserializer error"
}
}
impl fmt::Display for DeserializerError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
DeserializerError(msg) => write!(f, "{}", msg),
}
}
}
impl From<de::value::Error> for DeserializerError {
#[inline]
fn from(e: de::value::Error) -> DeserializerError {
DeserializerError(e.to_string())
}
}
impl ConstValue {
#[inline]
fn unexpected(&self) -> Unexpected {
match self {
ConstValue::Null => Unexpected::Unit,
ConstValue::Number(_) => Unexpected::Other("number"),
ConstValue::String(v) => Unexpected::Str(v),
ConstValue::Boolean(v) => Unexpected::Bool(*v),
ConstValue::Binary(v) => Unexpected::Bytes(v),
ConstValue::Enum(v) => Unexpected::Str(v),
ConstValue::List(_) => Unexpected::Seq,
ConstValue::Object(_) => Unexpected::Map,
}
}
}
fn visit_array<'de, V>(array: Vec<ConstValue>, visitor: V) -> Result<V::Value, DeserializerError>
where
V: Visitor<'de>,
{
let len = array.len();
let mut deserializer = SeqDeserializer::new(array);
let seq = visitor.visit_seq(&mut deserializer)?;
let remaining = deserializer.iter.len();
if remaining == 0 {
Ok(seq)
} else {
Err(DeserializerError::invalid_length(
len,
&"fewer elements in array",
))
}
}
fn visit_object<'de, V>(
object: IndexMap<Name, ConstValue>,
visitor: V,
) -> Result<V::Value, DeserializerError>
where
V: Visitor<'de>,
{
let len = object.len();
let mut deserializer = MapDeserializer::new(object);
let map = visitor.visit_map(&mut deserializer)?;
let remaining = deserializer.iter.len();
if remaining == 0 {
Ok(map)
} else {
Err(DeserializerError::invalid_length(
len,
&"fewer elements in map",
))
}
}
impl<'de> de::Deserializer<'de> for ConstValue {
type Error = DeserializerError;
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error>
where
V: Visitor<'de>,
{
match self {
ConstValue::Null => visitor.visit_unit(),
ConstValue::Number(v) => v
.deserialize_any(visitor)
.map_err(|err| DeserializerError(err.to_string())),
ConstValue::String(v) => visitor.visit_str(&v),
ConstValue::Boolean(v) => visitor.visit_bool(v),
ConstValue::Binary(bytes) => visitor.visit_bytes(&bytes),
ConstValue::Enum(v) => visitor.visit_str(v.as_str()),
ConstValue::List(v) => visit_array(v, visitor),
ConstValue::Object(v) => visit_object(v, visitor),
}
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf unit unit_struct seq tuple
tuple_struct map struct identifier ignored_any
}
#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error>
where
V: Visitor<'de>,
{
match self {
ConstValue::Null => visitor.visit_none(),
_ => visitor.visit_some(self),
}
}
#[inline]
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<<V as Visitor<'de>>::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
fn deserialize_enum<V>(
self,
_name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<<V as Visitor<'de>>::Value, Self::Error>
where
V: Visitor<'de>,
{
let (variant, value) = match self {
ConstValue::Object(value) => {
let mut iter = value.into_iter();
let (variant, value) = match iter.next() {
Some(v) => v,
None => {
return Err(serde::de::Error::invalid_value(
Unexpected::Map,
&"map with a single key",
));
}
};
// enums are encoded in json as maps with a single key:value pair
if iter.next().is_some() {
return Err(serde::de::Error::invalid_value(
Unexpected::Map,
&"map with a single key",
));
}
(variant, Some(value))
}
ConstValue::String(variant) => (Name::new(variant), None),
ConstValue::Enum(variant) => (variant, None),
other => {
return Err(DeserializerError::invalid_type(
other.unexpected(),
&"string or map",
));
}
};
visitor.visit_enum(EnumDeserializer { variant, value })
}
#[inline]
fn is_human_readable(&self) -> bool {
true
}
}
struct EnumDeserializer {
variant: Name,
value: Option<ConstValue>,
}
impl<'de> EnumAccess<'de> for EnumDeserializer {
type Error = DeserializerError;
type Variant = VariantDeserializer;
#[inline]
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, VariantDeserializer), DeserializerError>
where
V: DeserializeSeed<'de>,
{
let variant = self.variant.into_deserializer();
let visitor = VariantDeserializer { value: self.value };
seed.deserialize(variant).map(|v| (v, visitor))
}
}
impl<'de> IntoDeserializer<'de, DeserializerError> for ConstValue {
type Deserializer = Self;
fn into_deserializer(self) -> Self::Deserializer {
self
}
}
struct VariantDeserializer {
value: Option<ConstValue>,
}
impl<'de> VariantAccess<'de> for VariantDeserializer {
type Error = DeserializerError;
#[inline]
fn unit_variant(self) -> Result<(), DeserializerError> {
match self.value {
Some(value) => Deserialize::deserialize(value),
None => Ok(()),
}
}
#[inline]
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, DeserializerError>
where
T: DeserializeSeed<'de>,
{
match self.value {
Some(value) => seed.deserialize(value),
None => Err(DeserializerError::invalid_type(
Unexpected::UnitVariant,
&"newtype variant",
)),
}
}
fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, DeserializerError>
where
V: Visitor<'de>,
{
match self.value {
Some(ConstValue::List(v)) => {
serde::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
}
Some(other) => Err(serde::de::Error::invalid_type(
other.unexpected(),
&"tuple variant",
)),
None => Err(DeserializerError::invalid_type(
Unexpected::UnitVariant,
&"tuple variant",
)),
}
}
fn struct_variant<V>(
self,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, DeserializerError>
where
V: Visitor<'de>,
{
match self.value {
Some(ConstValue::Object(v)) => {
serde::Deserializer::deserialize_any(MapDeserializer::new(v), visitor)
}
Some(other) => Err(DeserializerError::invalid_type(
other.unexpected(),
&"struct variant",
)),
None => Err(DeserializerError::invalid_type(
Unexpected::UnitVariant,
&"struct variant",
)),
}
}
}
struct SeqDeserializer {
iter: vec::IntoIter<ConstValue>,
}
impl SeqDeserializer {
fn new(vec: Vec<ConstValue>) -> Self {
SeqDeserializer {
iter: vec.into_iter(),
}
}
}
impl<'de> serde::Deserializer<'de> for SeqDeserializer {
type Error = DeserializerError;
#[inline]
fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, DeserializerError>
where
V: Visitor<'de>,
{
let len = self.iter.len();
if len == 0 {
visitor.visit_unit()
} else {
let ret = visitor.visit_seq(&mut self)?;
let remaining = self.iter.len();
if remaining == 0 {
Ok(ret)
} else {
Err(DeserializerError::invalid_length(
len,
&"fewer elements in array",
))
}
}
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
impl<'de> SeqAccess<'de> for SeqDeserializer {
type Error = DeserializerError;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, DeserializerError>
where
T: DeserializeSeed<'de>,
{
match self.iter.next() {
Some(value) => seed.deserialize(value).map(Some),
None => Ok(None),
}
}
#[inline]
fn size_hint(&self) -> Option<usize> {
match self.iter.size_hint() {
(lower, Some(upper)) if lower == upper => Some(upper),
_ => None,
}
}
}
struct MapDeserializer {
iter: <IndexMap<Name, ConstValue> as IntoIterator>::IntoIter,
value: Option<ConstValue>,
}
impl MapDeserializer {
#[inline]
fn new(map: IndexMap<Name, ConstValue>) -> Self {
MapDeserializer {
iter: map.into_iter(),
value: None,
}
}
}
impl<'de> MapAccess<'de> for MapDeserializer {
type Error = DeserializerError;
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, DeserializerError>
where
T: DeserializeSeed<'de>,
{
match self.iter.next() {
Some((key, value)) => {
self.value = Some(value);
let key_de = MapKeyDeserializer { key };
seed.deserialize(key_de).map(Some)
}
None => Ok(None),
}
}
#[inline]
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, DeserializerError>
where
T: DeserializeSeed<'de>,
{
match self.value.take() {
Some(value) => seed.deserialize(value),
None => Err(serde::de::Error::custom("value is missing")),
}
}
#[inline]
fn size_hint(&self) -> Option<usize> {
match self.iter.size_hint() {
(lower, Some(upper)) if lower == upper => Some(upper),
_ => None,
}
}
}
impl<'de> serde::Deserializer<'de> for MapDeserializer {
type Error = DeserializerError;
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, DeserializerError>
where
V: Visitor<'de>,
{
visitor.visit_map(self)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
struct MapKeyDeserializer {
key: Name,
}
impl<'de> serde::Deserializer<'de> for MapKeyDeserializer {
type Error = DeserializerError;
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, DeserializerError>
where
V: Visitor<'de>,
{
NameDeserializer::new(self.key).deserialize_any(visitor)
}
#[inline]
fn deserialize_enum<V>(
self,
name: &'static str,
variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, DeserializerError>
where
V: Visitor<'de>,
{
self.key
.into_deserializer()
.deserialize_enum(name, variants, visitor)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string
bytes byte_buf unit unit_struct seq tuple option newtype_struct
tuple_struct map struct identifier ignored_any
}
}
struct NameDeserializer {
value: Name,
}
impl NameDeserializer {
#[inline]
fn new(value: Name) -> Self {
NameDeserializer { value }
}
}
impl<'de> de::Deserializer<'de> for NameDeserializer {
type Error = DeserializerError;
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, DeserializerError>
where
V: de::Visitor<'de>,
{
visitor.visit_string(self.value.to_string())
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf option unit unit_struct newtype_struct seq tuple enum
tuple_struct map struct identifier ignored_any
}
}
/// Interpret a `ConstValue` as an instance of type `T`.
#[inline]
pub fn from_value<T: DeserializeOwned>(value: ConstValue) -> Result<T, DeserializerError> {
T::deserialize(value)
}
|
use super::*;
#[test]
fn with_number_atom_reference_function_port_pid_or_tuple_returns_false() {
run!(
|arc_process| {
(
strategy::term::map(arc_process.clone()),
strategy::term::number_atom_reference_function_port_pid_or_tuple(arc_process),
)
},
|(left, right)| {
prop_assert_eq!(result(left, right), false.into());
Ok(())
},
);
}
#[test]
fn with_smaller_map_right_returns_false() {
is_equal_or_less_than(
|_, process| process.map_from_slice(&[(Atom::str_to_term("a"), process.integer(1))]),
false,
);
}
#[test]
fn with_same_size_map_with_lesser_keys_returns_false() {
is_equal_or_less_than(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("a"), process.integer(2)),
(Atom::str_to_term("b"), process.integer(3)),
])
},
false,
);
}
#[test]
fn with_same_size_map_with_same_keys_with_lesser_values_returns_false() {
is_equal_or_less_than(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("b"), process.integer(2)),
(Atom::str_to_term("c"), process.integer(2)),
])
},
false,
);
}
#[test]
fn with_same_value_map_returns_true() {
is_equal_or_less_than(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("b"), process.integer(2)),
(Atom::str_to_term("c"), process.integer(3)),
])
},
true,
);
}
#[test]
fn with_same_size_map_with_same_keys_with_greater_values_returns_true() {
is_equal_or_less_than(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("b"), process.integer(3)),
(Atom::str_to_term("c"), process.integer(4)),
])
},
true,
);
}
#[test]
fn with_same_size_map_with_greater_keys_returns_true() {
is_equal_or_less_than(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("c"), process.integer(2)),
(Atom::str_to_term("d"), process.integer(3)),
])
},
true,
);
}
#[test]
fn with_greater_size_map_returns_true() {
is_equal_or_less_than(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("a"), process.integer(1)),
(Atom::str_to_term("b"), process.integer(2)),
(Atom::str_to_term("c"), process.integer(3)),
])
},
true,
);
}
#[test]
fn with_map_right_returns_false() {
is_equal_or_less_than(|_, process| process.map_from_slice(&[]), false);
}
#[test]
fn with_list_or_bitstring_returns_true() {
run!(
|arc_process| {
(
strategy::term::map(arc_process.clone()),
strategy::term::list_or_bitstring(arc_process.clone()),
)
},
|(left, right)| {
prop_assert_eq!(result(left, right), true.into());
Ok(())
},
);
}
fn is_equal_or_less_than<R>(right: R, expected: bool)
where
R: FnOnce(Term, &Process) -> Term,
{
super::is_equal_or_less_than(
|process| {
process.map_from_slice(&[
(Atom::str_to_term("b"), process.integer(2)),
(Atom::str_to_term("c"), process.integer(3)),
])
},
right,
expected,
);
}
|
use decoder::MAX_COMPONENTS;
use idct::dequantize_and_idct_block;
use parser::Component;
use std::mem;
use std::sync::Arc;
pub struct RowData {
pub index: usize,
pub component: Component,
pub quantization_table: Arc<[u16; 64]>,
}
pub struct Worker {
offsets: Box<[usize]>,
results: Vec<Vec<u8>>,
components: Vec<Option<Component>>,
quantization_tables: Vec<Option<Arc<[u16; 64]>>>
}
impl Worker {
pub fn new() -> Self {
Worker {
offsets: vec![0; MAX_COMPONENTS].into_boxed_slice(),
results: vec![Vec::new(); MAX_COMPONENTS],
components: vec![None; MAX_COMPONENTS],
quantization_tables: vec![None; MAX_COMPONENTS],
}
}
pub fn start(&mut self, data: RowData) {
let offsets = &mut self.offsets;
let results = &mut self.results;
let components = &mut self.components;
let quantization_tables = &mut self.quantization_tables;
assert!(results[data.index].is_empty());
offsets[data.index] = 0;
results[data.index].resize(data.component.block_size.width as usize * data.component.block_size.height as usize * 64, 0u8);
components[data.index] = Some(data.component);
quantization_tables[data.index] = Some(data.quantization_table);
}
pub fn append_row(&mut self, index: usize, data: Vec<i16>) {
// Convert coefficients from a MCU row to samples.
let offsets = &mut self.offsets;
let results = &mut self.results;
let components = &mut self.components;
let quantization_tables = &mut self.quantization_tables;
let component = components[index].as_ref().unwrap();
let quantization_table = quantization_tables[index].as_ref().unwrap();
let block_count = component.block_size.width as usize * component.vertical_sampling_factor as usize;
let line_stride = component.block_size.width as usize * 8;
assert_eq!(data.len(), block_count * 64);
for i in 0 .. block_count {
let x = (i % component.block_size.width as usize) * 8;
let y = (i / component.block_size.width as usize) * 8;
dequantize_and_idct_block(&data[i * 64 .. (i + 1) * 64],
quantization_table,
line_stride,
&mut results[index][offsets[index] + y * line_stride + x ..]);
}
offsets[index] += data.len();
}
pub fn get_result(&mut self, index: usize) -> Vec<u8> {
mem::replace(&mut self.results[index], Vec::new())
}
}
|
use std::collections::VecDeque;
use flatbuffers::FlatBufferBuilder;
use super::{Bytes, LevelId, Timestamp};
use crate::error::Result;
use crate::file::FileManager;
#[derive(Default, PartialEq, Eq, Debug, Clone, Copy)]
pub struct LevelDesc {
start: Timestamp,
end: Timestamp,
id: LevelId,
}
impl From<protos::LevelDesc> for LevelDesc {
fn from(fb_desc: protos::LevelDesc) -> LevelDesc {
let time_range = fb_desc.time_range();
Self {
start: time_range.start().timestamp(),
end: time_range.end().timestamp(),
id: fb_desc.id().id(),
}
}
}
impl LevelDesc {
pub fn as_generated_type(&self) -> protos::LevelDesc {
let start = protos::Timestamp::new(self.start);
let end = protos::Timestamp::new(self.end);
let time_range = protos::TimeRange::new(&start, &end);
let id = protos::LevelId::new(self.id);
protos::LevelDesc::new(&time_range, &id)
}
#[inline]
pub fn is_timestamp_match(&self, timestamp: Timestamp) -> bool {
self.start <= timestamp && timestamp <= self.end
}
}
/// Metadata of every levels. Is a array-like container of [LevelDesc].
///
/// [LevelDesc] is arranged from old (smaller timestamp) to new
/// (larger timestamp).
#[derive(Debug, PartialEq, Eq)]
pub struct LevelInfo {
// todo: remove RwLock
infos: VecDeque<LevelDesc>,
}
impl LevelInfo {
pub fn encode(&self) -> Bytes {
let mut fbb = FlatBufferBuilder::new();
fbb.start_vector::<protos::LevelDesc>(self.infos.len());
for desc in &self.infos {
fbb.push(desc.as_generated_type());
}
let batch = fbb.end_vector::<protos::LevelDesc>(self.infos.len());
let infos =
protos::LevelInfo::create(&mut fbb, &protos::LevelInfoArgs { infos: Some(batch) });
fbb.finish(infos, None);
fbb.finished_data().to_vec()
}
pub fn decode(bytes: &[u8]) -> Self {
// for empty level-info file.
if bytes.is_empty() {
return Self {
infos: VecDeque::default(),
};
}
let fb_info = flatbuffers::root::<protos::LevelInfo<'_>>(bytes).unwrap();
let infos = fb_info
.infos()
.unwrap()
.to_owned()
.into_iter()
.rev() // `fbb.push()` in encode reversed the order
.map(LevelDesc::from)
.collect();
Self { infos }
}
/// Give a timestamp and find the level suits it.
///
/// Rick entries' timestamp will not present in level-info.
/// Thus if given timestamp is larger than the biggest timestamp recorded by
/// this level-info, `Some(0)` will be returned. `0` is a special [LevelId]
/// stands for Rick level.
pub fn get_level_id(&self, timestamp: Timestamp) -> Option<LevelId> {
// timestamp covered by rick will not present in level-info
if self.infos.is_empty() || timestamp > self.infos.back().unwrap().end {
return Some(0);
}
for desc in &self.infos {
if desc.is_timestamp_match(timestamp) {
return Some(desc.id);
}
}
None
}
/// Return new level id.
crate async fn add_level(
&mut self,
start: Timestamp,
end: Timestamp,
file_manager: &FileManager,
) -> Result<LevelId> {
let mut new_desc = LevelDesc { start, end, id: 0 };
let next_id = self.infos.back().map_or_else(|| 1, |desc| desc.id + 1);
new_desc.id = next_id;
self.infos.push_back(new_desc);
self.sync(file_manager).await?;
Ok(next_id)
}
crate async fn remove_last_level(&mut self, file_manager: &FileManager) -> Result<()> {
self.infos.pop_front();
self.sync(file_manager).await
}
/// Sync file infos to disk. Requires read lock.
async fn sync(&self, file_manager: &FileManager) -> Result<()> {
let bytes = self.encode();
file_manager.sync_level_info(bytes).await?;
Ok(())
}
#[cfg(test)]
fn new(descriptions: Vec<LevelDesc>) -> Self {
let infos = VecDeque::from(descriptions);
Self { infos }
}
}
#[cfg(test)]
mod test {
use glommio::LocalExecutor;
use tempfile::tempdir;
use super::*;
#[test]
fn level_desc_codec() {
let infos = LevelInfo::new(vec![
LevelDesc {
start: 21,
end: 40,
id: 4,
},
LevelDesc {
start: 100,
end: 200,
id: 8,
},
]);
let bytes = infos.encode();
let decoded = LevelInfo::decode(&bytes);
assert_eq!(decoded, infos);
}
#[test]
fn add_level() {
let ex = LocalExecutor::default();
ex.run(async {
let base_dir = tempdir().unwrap();
let file_manager = FileManager::with_base_dir(base_dir.path(), 1).unwrap();
let mut info = LevelInfo::new(vec![]);
info.add_level(0, 9, &file_manager).await.unwrap();
info.add_level(10, 19, &file_manager).await.unwrap();
info.add_level(20, 29, &file_manager).await.unwrap();
drop(info);
let info = file_manager.open_level_info().await.unwrap();
let infos: Vec<_> = info.infos.iter().copied().collect();
let expected = vec![
LevelDesc {
start: 0,
end: 9,
id: 1,
},
LevelDesc {
start: 10,
end: 19,
id: 2,
},
LevelDesc {
start: 20,
end: 29,
id: 3,
},
];
assert_eq!(infos, expected);
});
}
}
|
use scanner_proc_macro::insert_scanner;
#[insert_scanner]
fn main() {
let (n, m) = scan!((usize, usize));
let c = (0..n).map(|_| scan!(usize; m)).collect();
solve(n, m, c);
}
fn solve(n: usize, m: usize, c: Vec<Vec<usize>>) {
let k = 1_000_00;
let mut cnt = vec![0; k + 1];
let mut d_sum = vec![0; k + 1];
let mut ans = 0;
for i in 0..n {
for j in 0..m {
ans += i * cnt[c[i][j]] - d_sum[c[i][j]];
}
for j in 0..m {
cnt[c[i][j]] += 1;
d_sum[c[i][j]] += i;
}
}
let mut cnt = vec![0; k + 1];
let mut d_sum = vec![0; k + 1];
for j in 0..m {
for i in 0..n {
ans += j * cnt[c[i][j]] - d_sum[c[i][j]];
}
for i in 0..n {
cnt[c[i][j]] += 1;
d_sum[c[i][j]] += j;
}
}
println!("{}", ans);
}
|
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Clear {
All,
Bottom,
Line,
}
|
#[doc = "Reader of register C1PR2"]
pub type R = crate::R<u32, super::C1PR2>;
#[doc = "Writer for register C1PR2"]
pub type W = crate::W<u32, super::C1PR2>;
#[doc = "Register C1PR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::C1PR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `PR49`"]
pub type PR49_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PR49`"]
pub struct PR49_W<'a> {
w: &'a mut W,
}
impl<'a> PR49_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `PR51`"]
pub type PR51_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PR51`"]
pub struct PR51_W<'a> {
w: &'a mut W,
}
impl<'a> PR51_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
impl R {
#[doc = "Bit 17 - Configurable event inputs x+32 Pending bit"]
#[inline(always)]
pub fn pr49(&self) -> PR49_R {
PR49_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 19 - Configurable event inputs x+32 Pending bit"]
#[inline(always)]
pub fn pr51(&self) -> PR51_R {
PR51_R::new(((self.bits >> 19) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 17 - Configurable event inputs x+32 Pending bit"]
#[inline(always)]
pub fn pr49(&mut self) -> PR49_W {
PR49_W { w: self }
}
#[doc = "Bit 19 - Configurable event inputs x+32 Pending bit"]
#[inline(always)]
pub fn pr51(&mut self) -> PR51_W {
PR51_W { w: self }
}
}
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that literals in attributes don't parse without the feature gate.
// gate-test-attr_literals
#![feature(custom_attribute)]
#[fake_attr] // OK
#[fake_attr(100)]
//~^ ERROR non-string literals in attributes
#[fake_attr(1, 2, 3)]
//~^ ERROR non-string literals in attributes
#[fake_attr("hello")]
//~^ ERROR string literals in top-level positions, are experimental
#[fake_attr(name = "hello")] // OK
#[fake_attr(1, "hi", key = 12, true, false)]
//~^ ERROR non-string literals in attributes, or string literals in top-level positions
#[fake_attr(key = "hello", val = 10)]
//~^ ERROR non-string literals in attributes
#[fake_attr(key("hello"), val(10))]
//~^ ERROR non-string literals in attributes, or string literals in top-level positions
#[fake_attr(enabled = true, disabled = false)]
//~^ ERROR non-string literals in attributes
#[fake_attr(true)]
//~^ ERROR non-string literals in attributes
#[fake_attr(pi = 3.14159)]
//~^ ERROR non-string literals in attributes
#[fake_attr(b"hi")]
//~^ ERROR string literals in top-level positions, are experimental
#[fake_doc(r"doc")]
//~^ ERROR string literals in top-level positions, are experimental
struct Q { }
fn main() { }
|
// Based on devicemgmt.wsdl.xml
// This file is an example of how generated code will look like. It contains some comments
// to see the relation between xml's and Rust code.
// Quote from ONVIF core spec (5.5 messages):
//
// The WSDL message part element is used to define the actual format of the message.
// Although there can be multiple parts in a WSDL message, this specification follows the WS-I basic
// profile [WS-I BP 2.0] and does not allow more than one part element in a message.
// Hence we always use the same name (“parameters”) for the message part name. The following WSDL
// notation is used for ONVIF specifications:
//
// <message name="’Operation_Name’Request”>
// <part name="parameters" element="’prefix’:’Operation_Name’"/>
// </message>
//
// respective,
// <message name="’Operation_Name’Response”>
// <part name="parameters" element="’prefix’:’Operation_Name’Response”/>
// </message>
//
// where 'prefix' is the prefix for the namespace in which the message is defined.
//
//
// So according to the spec we will use only single-part messages.
// Quote from ONVIF core spec (5.6.2 One-way operation type):
// <operation name=”’Operation_Name’”>
// <input message=”’prefix’:’Operation_Name’”/>
// </operation>
//
// Quote from ONVIF core spec (5.6.3 Request-response operation type):
// <operation name=”’Operation_Name’”>
// <input message=”’prefix’:’Operation_Name’”/>
// <output message=”’prefix’:’Operation_Name’Response”/>
// <fault name> = “Fault” message = “’prefix’:’FaultMessage_Name’”>
// </operation>
//
//
// So we have 2 types of operations, some with fault message.
// But after some grepping over WSDLs we can state:
// - Only event.wsdl has one-way operations.
// - Only event.wsdl has operations with fault messages.
// - All other wsdl's except event.wsdl (25 in total) have only req-rep operations
// with exactly 1 input and 1 output message.
//
// For now it looks like we can divide all files into 2 categories:
// - event.wsdl. It is a little bit more complex case for code generation.
// - everything else. Simpler case. Let current file (devicegmt.rs) be an example of this group.
use crate::schema::onvif as tt;
use crate::transport;
use std::io::{Read, Write};
use yaserde::{YaDeserialize, YaSerialize};
// <xs:element name="GetSystemDateAndTime">
// <xs:complexType>
// <xs:sequence/>
// </xs:complexType>
// </xs:element>
#[derive(Default, PartialEq, Debug, YaSerialize)]
#[yaserde(
prefix = "tds",
namespace = "tds: http://www.onvif.org/ver10/device/wsdl"
)]
pub struct GetSystemDateAndTime {}
// <xs:element name="GetSystemDateAndTimeResponse">
// <xs:complexType>
// <xs:sequence>
// <xs:element name="SystemDateAndTime" type="tt:SystemDateTime">
// <xs:annotation>
// <xs:documentation>Contains information whether system date and time are set manually or by NTP, daylight savings is on or off, time zone in POSIX 1003.1 format and system date and time in UTC and also local system date and time.</xs:documentation>
// </xs:annotation>
// </xs:element>
// </xs:sequence>
// </xs:complexType>
// </xs:element>
// Contains information whether system date and time are set manually or by NTP,
// daylight savings is on or off, time zone in POSIX 1003.1 format and system date
// and time in UTC and also local system date and time.
#[derive(Default, PartialEq, Debug, YaDeserialize)]
#[yaserde(
prefix = "tds",
namespace = "tds: http://www.onvif.org/ver10/device/wsdl"
)]
pub struct GetSystemDateAndTimeResponse {
#[yaserde(prefix = "tds", rename = "SystemDateAndTime")]
pub system_date_and_time: tt::SystemDateTime,
}
// <wsdl:operation name="GetSystemDateAndTime">
// <wsdl:documentation>This operation gets the device system date and time. The device shall support the return of
// the daylight saving setting and of the manual system date and time (if applicable) or indication
// of NTP time (if applicable) through the GetSystemDateAndTime command.<br/>
// A device shall provide the UTCDateTime information.
// </wsdl:documentation>
// <wsdl:input message="tds:GetSystemDateAndTimeRequest"/>
// <wsdl:output message="tds:GetSystemDateAndTimeResponse"/>
// </wsdl:operation>
//
// <wsdl:message name="GetSystemDateAndTimeRequest">
// <wsdl:part name="parameters" element="tds:GetSystemDateAndTime"/>
// </wsdl:message>
//
// <wsdl:message name="GetSystemDateAndTimeResponse">
// <wsdl:part name="parameters" element="tds:GetSystemDateAndTimeResponse"/>
// </wsdl:message>
// This operation gets the device system date and time. The device shall support the return of
// the daylight saving setting and of the manual system date and time (if applicable) or
// indication of NTP time (if applicable) through the GetSystemDateAndTime command.
// A device shall provide the UTCDateTime information.
pub async fn get_system_date_and_time<T: transport::Transport>(
transport: &T,
request: &GetSystemDateAndTime,
) -> Result<GetSystemDateAndTimeResponse, transport::Error> {
transport::request(transport, request).await
}
#[derive(Default, PartialEq, Debug, YaSerialize)]
#[yaserde(
prefix = "tds",
namespace = "tds: http://www.onvif.org/ver10/device/wsdl"
)]
pub struct SetHostname {
#[yaserde(prefix = "tds", rename = "Name")]
pub name: String,
}
#[derive(Default, PartialEq, Debug, YaDeserialize)]
#[yaserde(
prefix = "tds",
namespace = "tds: http://www.onvif.org/ver10/device/wsdl"
)]
pub struct SetHostnameResponse {}
pub async fn set_hostname<T: transport::Transport>(
transport: &T,
request: &SetHostname,
) -> Result<SetHostnameResponse, transport::Error> {
transport::request(transport, request).await
}
#[derive(Default, PartialEq, Debug, YaSerialize)]
#[yaserde(
prefix = "tds",
namespace = "tds: http://www.onvif.org/ver10/device/wsdl"
)]
pub struct GetHostname {}
#[derive(Default, PartialEq, Debug, YaDeserialize)]
#[yaserde(
prefix = "tds",
namespace = "tds: http://www.onvif.org/ver10/device/wsdl"
)]
pub struct GetHostnameResponse {
#[yaserde(prefix = "tds", rename = "HostnameInformation")]
pub hostname_information: tt::HostnameInformation,
}
pub async fn get_hostname<T: transport::Transport>(
transport: &T,
request: &GetHostname,
) -> Result<GetHostnameResponse, transport::Error> {
transport::request(transport, request).await
}
// <xs:element name="GetDeviceInformation">
// <xs:complexType>
// <xs:sequence/>
// </xs:complexType>
// </xs:element>
#[derive(Default, PartialEq, Debug, YaSerialize)]
#[yaserde(
prefix = "tds",
namespace = "tds: http://www.onvif.org/ver10/device/wsdl"
)]
pub struct GetDeviceInformation {}
// <xs:element name="GetDeviceInformationResponse">
// <xs:complexType>
// <xs:sequence>
// <xs:element name="Manufacturer" type="xs:string">
// <xs:annotation>
// <xs:documentation>The manufactor of the device.</xs:documentation>
// </xs:annotation>
// </xs:element>
// <xs:element name="Model" type="xs:string">
// <xs:annotation>
// <xs:documentation>The device model.</xs:documentation>
// </xs:annotation>
// </xs:element>
// <xs:element name="FirmwareVersion" type="xs:string">
// <xs:annotation>
// <xs:documentation>The firmware version in the device.</xs:documentation>
// </xs:annotation>
// </xs:element>
// <xs:element name="SerialNumber" type="xs:string">
// <xs:annotation>
// <xs:documentation>The serial number of the device.</xs:documentation>
// </xs:annotation>
// </xs:element>
// <xs:element name="HardwareId" type="xs:string">
// <xs:annotation>
// <xs:documentation>The hardware ID of the device.</xs:documentation>
// </xs:annotation>
// </xs:element>
// </xs:sequence>
// </xs:complexType>
// </xs:element>
#[derive(Default, PartialEq, Debug, YaDeserialize)]
#[yaserde(
prefix = "tds",
namespace = "tds: http://www.onvif.org/ver10/device/wsdl"
)]
pub struct GetDeviceInformationResponse {
// The manufactor of the device.
#[yaserde(prefix = "tds", rename = "Manufacturer")]
pub manufacturer: String,
// The device model.
#[yaserde(prefix = "tds", rename = "Model")]
pub model: String,
// The firmware version in the device.
#[yaserde(prefix = "tds", rename = "FirmwareVersion")]
pub firmware_version: String,
// The serial number of the device.
#[yaserde(prefix = "tds", rename = "SerialNumber")]
pub serial_number: String,
// The hardware ID of the device.
#[yaserde(prefix = "tds", rename = "HardwareId")]
pub hardware_id: String,
}
// <wsdl:operation name="GetDeviceInformation">
// <wsdl:documentation>This operation gets basic device information from the device.</wsdl:documentation>
// <wsdl:input message="tds:GetDeviceInformationRequest"/>
// <wsdl:output message="tds:GetDeviceInformationResponse"/>
// </wsdl:operation>
//
// <wsdl:message name="GetDeviceInformationRequest">
// <wsdl:part name="parameters" element="tds:GetDeviceInformation"/>
// </wsdl:message>
//
// <wsdl:message name="GetDeviceInformationResponse">
// <wsdl:part name="parameters" element="tds:GetDeviceInformationResponse"/>
// </wsdl:message>
// This operation gets basic device information from the device.
pub async fn get_device_information<T: transport::Transport>(
transport: &T,
request: &GetDeviceInformation,
) -> Result<GetDeviceInformationResponse, transport::Error> {
transport::request(transport, request).await
}
|
//! C symbols for FFI.
#![allow(non_upper_case_globals)]
extern crate libc;
use std;
use std::ffi::CString;
use super::layer::Layer;
use super::payload::Payload;
use super::attr::Attr;
use super::context::Context;
use super::token::Token;
use super::logger::Metadata;
macro_rules! def_func {
( $( $x:ident, $y:ty ); *; ) => {
$(
pub(crate) static mut $x: Option<$y> = None;
)*
pub fn init(resolve: fn(*const libc::c_char) -> *const ()) {
unsafe {
$(
$x = std::mem::transmute(
resolve(CString::new(stringify!($x)).unwrap().as_ptr()));
$x.expect(concat!("symbol not found: ", stringify!($x)));
)*
}
}
};
}
def_func!(
Token_literal_, extern "C" fn(*const libc::c_char, libc::size_t) -> Token;
Token_string, extern "C" fn(Token) -> *const libc::c_char;
Context_getConfig, extern "C" fn(*const Context, *const libc::c_char, libc::size_t) -> *const libc::c_char;
Context_addLayerLinkage, extern "C" fn(*const Context, Token, u64, *mut Layer);
Layer_attr, extern "C" fn(*const Layer, Token) -> *const Attr;
Layer_payloads, extern "C" fn(*const Layer, *mut libc::size_t) -> *const *const Payload;
Layer_addLayer, extern "C" fn(*mut Layer, *mut Context, Token) -> *mut Layer;
Layer_addAttr, extern "C" fn(*mut Layer, *mut Context, Token) -> *mut Attr;
Layer_addAttrAlias, extern "C" fn(*mut Layer, *mut Context, Token, Token);
Layer_addPayload, extern "C" fn(*mut Layer, *mut Context) -> *mut Payload;
Layer_addError, extern "C" fn(*mut Layer, *mut Context, Token, *const libc::c_char, libc::size_t);
Layer_addTag, extern "C" fn(*mut Layer, *mut Context, Token);
Payload_addSlice, extern "C" fn(*mut Payload, (*const u8, usize));
Payload_slices, extern "C" fn(*const Payload, *mut libc::size_t) -> *const (*const u8, usize);
Payload_addAttr, extern "C" fn(*mut Payload, *mut Context, Token) -> *mut Attr;
Logger_log, extern "C" fn(*mut Context, *const libc::c_char, *const Metadata);
);
/// Define module entry point
#[macro_export]
macro_rules! plugkit_module(
($body:expr) => (
#[no_mangle]
pub extern "C" fn plugkit_v1_init(resolve: fn(*const libc::c_char) -> *const ()) {
plugkit::symbol::init(resolve);
fn init() {
$body
}
init();
}
)
);
|
#[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::IRQENABLE {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct AES_IRQENABLE_CONTEXT_INR {
bits: bool,
}
impl AES_IRQENABLE_CONTEXT_INR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_IRQENABLE_CONTEXT_INW<'a> {
w: &'a mut W,
}
impl<'a> _AES_IRQENABLE_CONTEXT_INW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_IRQENABLE_DATA_INR {
bits: bool,
}
impl AES_IRQENABLE_DATA_INR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_IRQENABLE_DATA_INW<'a> {
w: &'a mut W,
}
impl<'a> _AES_IRQENABLE_DATA_INW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 1);
self.w.bits |= ((value as u32) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_IRQENABLE_DATA_OUTR {
bits: bool,
}
impl AES_IRQENABLE_DATA_OUTR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_IRQENABLE_DATA_OUTW<'a> {
w: &'a mut W,
}
impl<'a> _AES_IRQENABLE_DATA_OUTW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_IRQENABLE_CONTEXT_OUTR {
bits: bool,
}
impl AES_IRQENABLE_CONTEXT_OUTR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_IRQENABLE_CONTEXT_OUTW<'a> {
w: &'a mut W,
}
impl<'a> _AES_IRQENABLE_CONTEXT_OUTW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Context In Interrupt Enable"]
#[inline(always)]
pub fn aes_irqenable_context_in(&self) -> AES_IRQENABLE_CONTEXT_INR {
let bits = ((self.bits >> 0) & 1) != 0;
AES_IRQENABLE_CONTEXT_INR { bits }
}
#[doc = "Bit 1 - Data In Interrupt Enable"]
#[inline(always)]
pub fn aes_irqenable_data_in(&self) -> AES_IRQENABLE_DATA_INR {
let bits = ((self.bits >> 1) & 1) != 0;
AES_IRQENABLE_DATA_INR { bits }
}
#[doc = "Bit 2 - Data Out Interrupt Enable"]
#[inline(always)]
pub fn aes_irqenable_data_out(&self) -> AES_IRQENABLE_DATA_OUTR {
let bits = ((self.bits >> 2) & 1) != 0;
AES_IRQENABLE_DATA_OUTR { bits }
}
#[doc = "Bit 3 - Context Out Interrupt Enable"]
#[inline(always)]
pub fn aes_irqenable_context_out(&self) -> AES_IRQENABLE_CONTEXT_OUTR {
let bits = ((self.bits >> 3) & 1) != 0;
AES_IRQENABLE_CONTEXT_OUTR { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Context In Interrupt Enable"]
#[inline(always)]
pub fn aes_irqenable_context_in(&mut self) -> _AES_IRQENABLE_CONTEXT_INW {
_AES_IRQENABLE_CONTEXT_INW { w: self }
}
#[doc = "Bit 1 - Data In Interrupt Enable"]
#[inline(always)]
pub fn aes_irqenable_data_in(&mut self) -> _AES_IRQENABLE_DATA_INW {
_AES_IRQENABLE_DATA_INW { w: self }
}
#[doc = "Bit 2 - Data Out Interrupt Enable"]
#[inline(always)]
pub fn aes_irqenable_data_out(&mut self) -> _AES_IRQENABLE_DATA_OUTW {
_AES_IRQENABLE_DATA_OUTW { w: self }
}
#[doc = "Bit 3 - Context Out Interrupt Enable"]
#[inline(always)]
pub fn aes_irqenable_context_out(&mut self) -> _AES_IRQENABLE_CONTEXT_OUTW {
_AES_IRQENABLE_CONTEXT_OUTW { w: self }
}
}
|
extern crate iris;
use iris::portfire;
#[cfg(feature="tts")]
use iris::tts;
fn say(message: &str) {
#[cfg(feature="tts")]
tts::say(message);
#[cfg(not(feature="tts"))]
println!("SAYING: {}", message);
}
fn main() {
#[cfg(feature="tts")]
tts::init();
say("Discovering portfires");
let boards = portfire::autodiscover().unwrap();
match boards.len() {
0 => { say("No boards found"); return; },
1 => say("One board found"),
i => say(&format!("{} boards found", i)),
}
for board in boards {
say("Pinging");
match board.ping() {
Ok(_) => say("OK"),
Err(_) => say("Error"),
}
say("Checking bus voltage");
match board.bus_voltage() {
Ok(v) => say(&format!("{:.0} volt", v)),
Err(_) => say("Error"),
}
say("Checking continuities");
let conts = board.continuities().unwrap();
let channels: Vec<String> = conts.iter()
.enumerate()
.filter(|&(_, cont)| *cont != 255)
.map(|(idx, _)| (idx+1).to_string())
.collect();
if channels.len() == 1 {
say("No channels connected");
} else {
say(&format!("channels {} connected", channels.join(",")));
}
say("Arming");
match board.arm() {
Ok(_) => say("OK"),
Err(_) => say("Error"),
}
say("Checking bus voltage");
match board.bus_voltage() {
Ok(v) => say(&format!("{:.0} volt", v)),
Err(_) => say("Error"),
}
say("Disarming");
match board.disarm() {
Ok(_) => say("OK"),
Err(_) => say("Error"),
}
}
}
|
use common::aoc::{load_input, run_many, print_result, print_time, print_result_multiline};
use common::intcode::{VM, StepResult};
use std::collections::{HashSet, HashMap};
use common::grid::Grid;
fn main() {
let input = load_input("day11");
let (vm, dur_parse) = run_many(10000, || VM::parse(input.trim_end_matches('\n')));
let ((_, res_part1), dur_part1) = run_many(10, || part1(vm.clone(), 0));
let (res_part2, dur_part2) = run_many(10, || part2(vm.clone()));
print_result("P1", res_part1);
print_result_multiline("P2", res_part2);
print_time("Parse", dur_parse);
print_time("P1", dur_part1);
print_time("P2", dur_part2);
}
const DIRECTIONS: [(isize, isize); 4] = [
(0, -1),
(1, 0),
(0, 1),
(-1, 0),
];
const DEFAULT_PAINT: i64 = 0;
fn part1(mut vm: VM, starting_color: i64) -> (HashMap<(isize, isize), i64>, usize) {
let mut paint_map: HashMap<(isize, isize), i64> = HashMap::with_capacity(128);
let mut x = 0;
let mut y = 0;
let mut dir_index = 0;
vm.push_input(starting_color);
loop {
let result = vm.run();
if result == StepResult::Exit {
break;
}
let output = vm.read_output();
let color = output[0];
let dir_change = output[1];
dir_index = (dir_index + if dir_change == 1 { 1 } else { 3 }) % 4;
match paint_map.get_mut(&(x, y)) {
Some(v) => *v = color,
None => {
paint_map.insert((x, y), color);
}
}
let (dx, dy) = DIRECTIONS[dir_index];
x += dx;
y += dy;
vm.push_input(*paint_map.get(&(x, y)).unwrap_or(&DEFAULT_PAINT));
}
let count = paint_map.len();
(paint_map, count)
}
fn part2(mut vm: VM) -> String {
let (mut paint_map, _) = part1(vm, 1);
// Find boundaries
let mut tlx = 0;
let mut tly = 0;
let mut brx = 0;
let mut bry = 0;
for (x, y) in paint_map.keys() {
if *x < tlx {
tlx = *x;
}
if *x > brx {
brx = *x;
}
if *y < tly {
tly = *y;
}
if *y > bry {
bry = *y;
}
}
let width = (brx - tlx) as usize;
let height = (bry - tly) as usize;
let mut grid = Grid::new(width+1, height+2, -tlx, -tly, '#');
for ((x, y), color) in paint_map.iter() {
if *color == 0 {
grid.set(*x, *y, '.');
}
}
let mut result = String::with_capacity((width * height) + height);
for y in 0..=(height as isize) {
for x in 0..=(width as isize) {
result.push(grid.get(x + tlx, y + tly));
}
result.push('\n');
}
result
} |
use std::{env, ffi::OsString, fmt, io, path::PathBuf, process::ExitStatus, string::FromUtf8Error};
use crate::{Cmd, CmdData};
/// `Result` from std, with the error type defaulting to xshell's [`Error`].
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// An error returned by an `xshell` operation.
pub struct Error {
kind: Box<ErrorKind>,
}
/// Note: this is intentionally not public.
enum ErrorKind {
CurrentDir { err: io::Error, path: Option<PathBuf> },
Var { err: env::VarError, var: OsString },
ReadFile { err: io::Error, path: PathBuf },
ReadDir { err: io::Error, path: PathBuf },
WriteFile { err: io::Error, path: PathBuf },
CopyFile { err: io::Error, src: PathBuf, dst: PathBuf },
HardLink { err: io::Error, src: PathBuf, dst: PathBuf },
CreateDir { err: io::Error, path: PathBuf },
RemovePath { err: io::Error, path: PathBuf },
CmdStatus { cmd: CmdData, status: ExitStatus },
CmdIo { err: io::Error, cmd: CmdData },
CmdUtf8 { err: FromUtf8Error, cmd: CmdData },
CmdStdin { err: io::Error, cmd: CmdData },
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
let kind = Box::new(kind);
Error { kind }
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &*self.kind {
ErrorKind::CurrentDir { err, path } => {
let suffix =
path.as_ref().map_or(String::new(), |path| format!(" `{}`", path.display()));
write!(f, "failed to get current directory{suffix}: {err}")
}
ErrorKind::Var { err, var } => {
let var = var.to_string_lossy();
write!(f, "failed to get environment variable `{var}`: {err}")
}
ErrorKind::ReadFile { err, path } => {
let path = path.display();
write!(f, "failed to read file `{path}`: {err}")
}
ErrorKind::ReadDir { err, path } => {
let path = path.display();
write!(f, "failed read directory `{path}`: {err}")
}
ErrorKind::WriteFile { err, path } => {
let path = path.display();
write!(f, "failed to write file `{path}`: {err}")
}
ErrorKind::CopyFile { err, src, dst } => {
let src = src.display();
let dst = dst.display();
write!(f, "failed to copy `{src}` to `{dst}`: {err}")
}
ErrorKind::HardLink { err, src, dst } => {
let src = src.display();
let dst = dst.display();
write!(f, "failed hard link `{src}` to `{dst}`: {err}")
}
ErrorKind::CreateDir { err, path } => {
let path = path.display();
write!(f, "failed to create directory `{path}`: {err}")
}
ErrorKind::RemovePath { err, path } => {
let path = path.display();
write!(f, "failed to remove path `{path}`: {err}")
}
ErrorKind::CmdStatus { cmd, status } => match status.code() {
Some(code) => write!(f, "command exited with non-zero code `{cmd}`: {code}"),
#[cfg(unix)]
None => {
use std::os::unix::process::ExitStatusExt;
match status.signal() {
Some(sig) => write!(f, "command was terminated by a signal `{cmd}`: {sig}"),
None => write!(f, "command was terminated by a signal `{cmd}`"),
}
}
#[cfg(not(unix))]
None => write!(f, "command was terminated by a signal `{cmd}`"),
},
ErrorKind::CmdIo { err, cmd } => {
if err.kind() == io::ErrorKind::NotFound {
let prog = cmd.prog.display();
write!(f, "command not found: `{prog}`")
} else {
write!(f, "io error when running command `{cmd}`: {err}")
}
}
ErrorKind::CmdUtf8 { err, cmd } => {
write!(f, "failed to decode output of command `{cmd}`: {err}")
}
ErrorKind::CmdStdin { err, cmd } => {
write!(f, "failed to write to stdin of command `{cmd}`: {err}")
}
}?;
Ok(())
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl std::error::Error for Error {}
/// `pub(crate)` constructors, visible only in this crate.
impl Error {
pub(crate) fn new_current_dir(err: io::Error, path: Option<PathBuf>) -> Error {
ErrorKind::CurrentDir { err, path }.into()
}
pub(crate) fn new_var(err: env::VarError, var: OsString) -> Error {
ErrorKind::Var { err, var }.into()
}
pub(crate) fn new_read_file(err: io::Error, path: PathBuf) -> Error {
ErrorKind::ReadFile { err, path }.into()
}
pub(crate) fn new_read_dir(err: io::Error, path: PathBuf) -> Error {
ErrorKind::ReadDir { err, path }.into()
}
pub(crate) fn new_write_file(err: io::Error, path: PathBuf) -> Error {
ErrorKind::WriteFile { err, path }.into()
}
pub(crate) fn new_copy_file(err: io::Error, src: PathBuf, dst: PathBuf) -> Error {
ErrorKind::CopyFile { err, src, dst }.into()
}
pub(crate) fn new_hard_link(err: io::Error, src: PathBuf, dst: PathBuf) -> Error {
ErrorKind::HardLink { err, src, dst }.into()
}
pub(crate) fn new_create_dir(err: io::Error, path: PathBuf) -> Error {
ErrorKind::CreateDir { err, path }.into()
}
pub(crate) fn new_remove_path(err: io::Error, path: PathBuf) -> Error {
ErrorKind::RemovePath { err, path }.into()
}
pub(crate) fn new_cmd_status(cmd: &Cmd<'_>, status: ExitStatus) -> Error {
let cmd = cmd.data.clone();
ErrorKind::CmdStatus { cmd, status }.into()
}
pub(crate) fn new_cmd_io(cmd: &Cmd<'_>, err: io::Error) -> Error {
let cmd = cmd.data.clone();
ErrorKind::CmdIo { err, cmd }.into()
}
pub(crate) fn new_cmd_utf8(cmd: &Cmd<'_>, err: FromUtf8Error) -> Error {
let cmd = cmd.data.clone();
ErrorKind::CmdUtf8 { err, cmd }.into()
}
pub(crate) fn new_cmd_stdin(cmd: &Cmd<'_>, err: io::Error) -> Error {
let cmd = cmd.data.clone();
ErrorKind::CmdStdin { err, cmd }.into()
}
}
#[test]
fn error_send_sync() {
fn f<T: Send + Sync>() {}
f::<Error>();
}
|
use crate::stdio_server::input::{AutocmdEventType, PluginEvent};
use crate::stdio_server::plugin::{ClapAction, ClapPlugin, PluginId};
use crate::stdio_server::vim::Vim;
use crate::tools::ctags::{BufferTag, Scope};
use anyhow::Result;
use icon::IconType;
use serde::Serialize;
use std::collections::HashMap;
use std::path::Path;
#[derive(Serialize, Debug)]
struct ScopeRef<'a> {
name: &'a str,
scope_kind: &'a str,
scope_kind_icon: IconType,
}
impl<'a> ScopeRef<'a> {
fn from_scope(scope: &'a Scope) -> Self {
let scope_kind_icon = icon::tags_kind_icon(&scope.scope_kind);
Self {
name: &scope.scope,
scope_kind: &scope.scope_kind,
scope_kind_icon,
}
}
}
#[derive(Debug)]
pub struct CtagsPlugin {
vim: Vim,
last_cursor_tag: Option<BufferTag>,
buf_tags: HashMap<usize, Vec<BufferTag>>,
}
impl CtagsPlugin {
pub const ID: PluginId = PluginId::Ctags;
pub fn new(vim: Vim) -> Self {
Self {
vim,
last_cursor_tag: None,
buf_tags: HashMap::new(),
}
}
async fn on_cursor_moved(&mut self, bufnr: usize) -> Result<()> {
if let Some(buffer_tags) = self.buf_tags.get(&bufnr) {
let curlnum = self.vim.line(".").await?;
let idx = match buffer_tags.binary_search_by_key(&curlnum, |tag| tag.line_number) {
Ok(idx) => idx,
Err(idx) => match idx.checked_sub(1) {
Some(idx) => idx,
None => {
// Before the first tag.
self.vim.setbufvar(bufnr, "clap_current_symbol", {})?;
self.last_cursor_tag.take();
return Ok(());
}
},
};
if let Some(tag) = buffer_tags.get(idx) {
if let Some(last_cursor_tag) = &self.last_cursor_tag {
if last_cursor_tag == tag {
return Ok(());
}
}
self.vim.setbufvar(
bufnr,
"clap_current_symbol",
serde_json::json!({
"name": tag.name,
"line_number": tag.line_number,
"kind": tag.kind,
"kind_icon": icon::tags_kind_icon(&tag.kind),
"scope": tag.scope.as_ref().map(ScopeRef::from_scope),
}),
)?;
// Redraw the statusline to reflect the latest tag.
self.vim.exec("execute", ["redrawstatus"])?;
self.last_cursor_tag.replace(tag.clone());
} else {
self.vim.setbufvar(bufnr, "clap_current_symbol", {})?;
self.last_cursor_tag.take();
}
}
Ok(())
}
}
impl ClapAction for CtagsPlugin {}
#[async_trait::async_trait]
impl ClapPlugin for CtagsPlugin {
fn id(&self) -> PluginId {
Self::ID
}
async fn on_plugin_event(&mut self, plugin_event: PluginEvent) -> Result<()> {
use AutocmdEventType::{BufDelete, BufEnter, BufWritePost, CursorMoved};
let PluginEvent::Autocmd(autocmd_event) = plugin_event else {
return Ok(());
};
let (event_type, params) = autocmd_event;
let params: Vec<usize> = params.parse()?;
let bufnr = params
.into_iter()
.next()
.ok_or_else(|| anyhow::anyhow!("bufnr not found in params"))?;
match event_type {
BufEnter | BufWritePost => {
let file_path: String = self.vim.expand(format!("#{bufnr}:p")).await?;
if !Path::new(&file_path).exists() {
return Ok(());
}
let buffer_tags = crate::tools::ctags::fetch_buffer_tags(file_path)?;
self.buf_tags.insert(bufnr, buffer_tags);
self.on_cursor_moved(bufnr).await?;
}
BufDelete => {
self.buf_tags.remove(&bufnr);
}
CursorMoved => self.on_cursor_moved(bufnr).await?,
_ => {}
}
Ok(())
}
}
|
use borsh::{BorshSerialize,BorshDeserialize};
use crate::{
structs::{CustomerData,DriverData,RecordInstruction,SingleInstruction}
};
use{
solana_program::{
log::sol_log_compute_units,
account_info::{next_account_info,AccountInfo},
entrypoint,
entrypoint::ProgramResult,
msg,
program_error::ProgramError,
pubkey::Pubkey,
}
};
pub mod helper;
pub mod processor;
pub mod structs;
use std::io::ErrorKind::InvalidData;
// const DUMMY_TX_ID: &str = "0000000000000000000000000000000000000000000";
// const DUMMY_CREATED_ON: &str = "0000000000000000";
// const DUMMY_LATLONG: &str="00000000";
const DUMMY_COST: &str="000000000000";
const DUMMY_ADDRESS: &str = "00000000000000000000000000000000000000000000";
// const DUMMY_DISTANCE : &str="0000";
const KM_RATE: f32=0.01 ; //Sol
// const DUMMY_INSTRUCTION: &str = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
// #[derive(BorshSerialize,BorshDeserialize,Debug)]
// pub struct ProfileData{
// pub profile_hash: String,
// pub rides_hash: String,
// //pub rides: u8,
// pub updated_on: String,
// pub type: u8
// }
// const DUMMY_ADDRESS: &str= "00000000000000000000000000000000000000000000";
// const DUMMY_COST: &str= "00000000";
//Steps
//1 to create customer
//2 to create customer ride
//3 to create driver
//4 driver selects customers for ride -> customer account updates with driver and max cost
//5 customer select a driver -> driver account updates with customer confirmation -> if 2 confirm -> ride start & customer is notified
//6 driver ride per customer -> generate cost for customer
//not here but customer then transfers the money to driver
// #[derive(BorshSerialize,BorshDeserialize,Debug)]
// pub struct DriverData{
// pub profile_hash: String,
// pub updated_on: String
// }
// #[derive(BorshSerialize,BorshDeserialize,Debug)]
// pub struct AdminData{
// pub kmRate: String
// }
//break instruction
//record_type = 1 0-1
//user_type = 1 1-2
//profile_ hash = 43 2-45
//lats = 8*4 45-53,53-61,61-69,69-77
//dist = 4 77-81
//customer_count = 1 81-82
//updated_on = 16 82-98
//driver_address = 44 98-142
//customer address = 44 142-186
//total rides distance 186-190
//rides confirmed 190-194
// const DUMMY_HASH: &str="0000000000000000000000000000000000000000000";
// const DUMMY_TIME: &str="0000000000000000";
//ride states
// 0 not started , 1 as pending , 2 as started, 3 as end, 4 as paid
entrypoint!(process_instruction);
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8]
) -> ProgramResult {
//solana_logger::setup_with("solana=debug");
let account_iter=&mut accounts.iter();
// let instruction = RecordInstruction::try_from_slice(instruction_data).map_err(|err|{
// msg!("Attempt to deserialize data failed {:?}",err);
// ProgramError::InvalidInstructionData
// })?;
let instruction = SingleInstruction::try_from_slice(instruction_data).map_err(|err|{
msg!("Attempt to deserialize data failed {:?}",err);
ProgramError::InvalidInstructionData
})?;
let full_instruction = instruction.full_instruction;
let record_type= &full_instruction[0..1];
let user_type= &full_instruction[1..2];
msg!("instruction type { }",record_type);
match &record_type[..]{
//init customer/driver
"0" => {
if user_type==String::from("1")
{
let account=next_account_info(account_iter)?;
crate::processor::step0_1(account,program_id);
}
if user_type==String::from("2")
{
let account=next_account_info(account_iter)?;
crate::processor::step0_2(account,program_id);
}
}
//create customer
"1" => {
let account=next_account_info(account_iter)?;
crate::processor::step1(account,program_id,full_instruction);
}
//save new customer ride
"2" => {
let account=next_account_info(account_iter)?;
crate::processor::step2(account,program_id,full_instruction);
}
//save driver data
"3" => {
let account=next_account_info(account_iter)?;
crate::processor::step3(account,program_id,full_instruction);
},
//driver select customer for rides
//first is driver account
//then the customer
"4" => {
//let customer_ride_count = instruction.customer_count;
//let dist_f = instruction.distance.parse::<f32>().unwrap();
// let driver_base58=String::from(DUMMY_ADDRESS);
// let customer_base58=String::from(DUMMY_ADDRESS);
// //driver
let driver_account=next_account_info(account_iter)?;
let customer_account_1=next_account_info(account_iter)?;
crate::processor::step4(driver_account,customer_account_1,program_id,full_instruction);
}
"5"=>{
let customer_account_1=next_account_info(account_iter)?;
let driver_account=next_account_info(account_iter)?;
crate::processor::step5(customer_account_1,driver_account,program_id,full_instruction);
}
"6"=>{
let driver_account=next_account_info(account_iter)?;
let customer_account=next_account_info(account_iter)?;
// let customer_account_2=next_account_info(account_iter)?;
// let customer_account_3=next_account_info(account_iter)?;
crate::processor::step6_2(driver_account,customer_account,program_id,full_instruction);
}
"7"=>{
let driver_account=next_account_info(account_iter)?;
// let customer_account_2=next_account_info(account_iter)?;
// let customer_account_3=next_account_info(account_iter)?;
crate::processor::step7(driver_account,program_id,full_instruction);
}
"8"=>{
let driver_account=next_account_info(account_iter)?;
let customer_account=next_account_info(account_iter)?;
crate::processor::step8(driver_account,customer_account,program_id,full_instruction);
}
"9"=>{
let customer_account=next_account_info(account_iter)?;
let driver_account=next_account_info(account_iter)?;
crate::processor::step9(customer_account,driver_account,program_id,full_instruction);
}
_ => {
msg!("Instruction did not match");
}
}
// let account=next_account_info(account_iter)?;
// if account.owner!=program_id{
// msg!("This account {} is not owned by program {}",account.key,program_id);
// }
// //check if format of data is correct
// let instruction_data_profile=ProfileData::try_from_slice(instruction_data).map_err(|err|{
// msg!("Attempt to deserialized data failed {:?}",err);
// ProgramError::InvalidInstructionData
// })?;
// let mut existing_profile_data=ProfileData::try_from_slice(&account.data.borrow_mut()){
// Ok(data)=>data,
// Err(err)=>{
// panic!("Unknown error {:?}",err);
// }
// };
//get data pointer from account
// let data=&mut &mut account.data.borrow_mut();
//save instruction data to account data
// data[..instruction_data.len()].copy_from_slice(&instruction_data);
sol_log_compute_units();
// msg!("Data updated at time {}",instruction.record_type);
Ok(())
}
// Sanity tests
#[cfg(test)]
mod test {
use super::*;
use solana_program::clock::Epoch;
//use std::mem;
#[test]
fn test_1() {
let program_id = Pubkey::default();
let key = Pubkey::default();
let mut lamports = 0;
let customer_init_account = get_init_acccount();
let mut data =customer_init_account.try_to_vec().unwrap();
let owner = Pubkey::default();
let account = AccountInfo::new(
&key,
false,
true,
&mut lamports,
&mut data,
&owner,
false,
Epoch::default(),
);
let customer_init_driver = get_init_driver();
let mut data_2 =customer_init_driver.try_to_vec().unwrap();
let mut lamports_2 = 0;
let account_3 = AccountInfo::new(
&key,
false,
true,
&mut lamports_2,
&mut data_2,
&owner,
false,
Epoch::default(),
);
let archive_id = "abcdefghijabcdefghijabcdefghijabcdefghijabc";
let mut instruction_data_1 = get_empty_instruction();
instruction_data_1.record_type=String::from("1");
instruction_data_1.profile_hash=String::from(archive_id);
let instruct_data_u8=instruction_data_1.try_to_vec().unwrap();
let accounts = vec![account];
let mut account_data = CustomerData::try_from_slice(&accounts[0].data.borrow()).unwrap();
msg!("customer hash {:?}", account_data.profile_hash);
process_instruction(&program_id, &accounts, &instruct_data_u8).unwrap();
account_data = CustomerData::try_from_slice(&accounts[0].data.borrow()).unwrap();
let test_archive_id = account_data.profile_hash;
//let test_created_on = &chat_messages.created_on;
msg!("customer hash {:?}", test_archive_id);
// I added first data and expect it to contain the given data
assert_eq!(
String::from(archive_id).eq(&test_archive_id),
true
);
//test2
let mut instruction_data_2= get_empty_instruction();
instruction_data_2.record_type=String::from("2");
instruction_data_2.from_lat=String::from("00000001");
instruction_data_2.to_lat=String::from("00000002");
instruction_data_2.from_long=String::from("00000003");
instruction_data_2.to_long=String::from("00000004");
instruction_data_2.dist= String::from("5.40");
let instruct_data_u8_2=instruction_data_2.try_to_vec().unwrap();
//let accounts = vec![account];
//msg!("customer hash {:?}", account_data.from_lat);
process_instruction(&program_id, &accounts, &instruct_data_u8_2).unwrap();
account_data = CustomerData::try_from_slice(&accounts[0].data.borrow()).unwrap();
let test_from_lat = account_data.from_lat;
//let test_created_on = &chat_messages.created_on;
msg!("customer hash {:?}", test_archive_id);
// I added first data and expect it to contain the given data
assert_eq!(
String::from("00000001").eq(&test_from_lat),
true
);
//test3
let archive_id_2 = "abcdefghijabcdefghijabcdefghijabcdefg111111";
let mut instruction_data_3 = get_empty_instruction();
instruction_data_3.record_type=String::from("3");
instruction_data_3.profile_hash=String::from(archive_id_2);
let instruct_data_u8_3=instruction_data_3.try_to_vec().unwrap();
let accounts_3 = vec![account_3];
let mut account_data_3 = DriverData::try_from_slice(&accounts_3[0].data.borrow()).unwrap();
msg!("driver hash {:?}", account_data_3.profile_hash);
process_instruction(&program_id, &accounts_3, &instruct_data_u8_3).unwrap();
account_data_3 = DriverData::try_from_slice(&accounts_3[0].data.borrow()).unwrap();
let test_archive_id_3 = account_data_3.profile_hash;
//let test_created_on = &chat_messages.created_on;
msg!("driver hash {:?}", test_archive_id_3);
// I added first data and expect it to contain the given data
assert_eq!(
String::from(archive_id_2).eq(&test_archive_id_3),
true
);
//test4
// let mut instruction_data_4 = get_empty_instruction();
// instruction_data_4.record_type=String::from("4");
// instruction_data_4.dist=String::from("0010");
// instruction_data_4.driver_address=String::from("00000000000000000000000000000000000000000001");
// instruction_data_4.customer_address=String::from("00000000000000000000000000000000000000000002");
// let instruct_data_u8_4=instruction_data_4.try_to_vec().unwrap();
// //let accounts_4 = vec![account, account_3];
// process_instruction(&program_id, &accounts, &instruct_data_u8_4).unwrap();
// let mut account_data_c_4 = CustomerData::try_from_slice(&accounts[0].data.borrow()).unwrap();
// let mut account_data_d_4 = DriverData::try_from_slice(&accounts[1].data.borrow()).unwrap();
// let customer_driver_address_4 = account_data_c_4.driver_address_1;
// let driver_customer_address_4 = account_data_d_4.customer_1;
// assert_eq!(
// String::from("00000000000000000000000000000000000000000001").eq(&customer_driver_address_4),
// true
// );
// assert_eq!(
// String::from("00000000000000000000000000000000000000000002").eq(&driver_customer_address_4),
// true
// );
// assert_eq!(
// String::from(created_on).eq(test_created_on),
// true
// );
}
}
|
use std::collections::hash_map::*;
use std::fs::File;
use std::env;
use std::io::{self, BufReader};
use hangouts_json_parser::{raw, Hangouts};
fn usage() {
eprintln!("usage: {} <json path> <participant name>", env::args().next().unwrap());
}
fn chrono(parts: Result<(i64, u32), std::num::ParseIntError>) -> chrono::DateTime<chrono::Utc> {
let (secs, nsecs) = parts.expect("bad timestamp");
chrono::TimeZone::timestamp(&chrono::Utc, secs, nsecs)
}
fn main() -> Result<(), io::Error> {
let path = env::args_os().nth(1).unwrap_or_else(|| {
usage();
std::process::exit(2);
});
let participant_name = env::args().nth(2).unwrap_or_else(|| {
usage();
std::process::exit(2);
});
let mut hangouts: Hangouts = serde_json::from_reader(BufReader::new(File::open(path)?))?;
let convo = hangouts.conversations
.iter_mut()
.find(|convo|
convo.header.details.participant_data.iter().any(|p|
p.fallback_name.as_ref() == Some(&participant_name)))
.unwrap_or_else(|| {
eprintln!("No matching conversation found with a person named {:?}", participant_name);
std::process::exit(1);
});
let names: HashMap<raw::ParticipantId, String> = convo.header.details.participant_data
.iter()
.map(|p| (p.id.clone(), p.fallback_name.as_deref().unwrap_or("[unknown]").to_owned()))
.collect();
convo.events.sort_unstable_by_key(|event| event.header.timestamp.clone());
for event in &convo.events {
let dt = chrono(event.header.timestamp()).format("%Y-%m-%d %H:%M:%S");
let name = &names[&event.header.sender_id];
let text = match event.data {
raw::EventData::ChatMessage { ref message_content, .. } => {
let mut combined = String::new();
for segment in &message_content.segments {
match segment {
raw::ChatSegment::Text { ref text, formatting: _ } => {
//combined += &format!("[text: {}]", text);
combined += text;
}
raw::ChatSegment::Link {
text: _,
ref link_data,
formatting: _,
} => {
combined += &format!("[link: {:?}]", link_data);
}
raw::ChatSegment::LineBreak { ref text } => {
if let Some(text) = text {
combined += text;
} else {
combined.push('\n');
}
}
}
}
for attachment in &message_content.attachments {
combined += &format!("[an attachment: {:#?}]", attachment);
}
combined
}
raw::EventData::HangoutEvent { ref data, .. } => {
match data {
raw::HangoutEvent::StartHangout => "[call started]".to_owned(),
raw::HangoutEvent::EndHangout { ref hangout_duration_secs } => {
format!("[call ended; duration was {} seconds", hangout_duration_secs)
}
}
}
raw::EventData::MembershipChange { .. } => {
format!("[membership change: {:#?}]", event.data)
}
raw::EventData::ConversationRename { ref old_name, ref new_name } => {
format!("[conversation rename from {:?} to {:?}]", old_name, new_name)
}
};
println!("[{}] {}: {}", dt, name, text);
}
Ok(())
}
|
error_chain! {
foreign_links {
Io(::std::io::Error) #[cfg(unix)];
SerdeJson(::serde_json::error::Error);
}
errors {
ConanNotInPath {
display("Conan was not found in your path.")
}
ConanInstallFailure(o: ::std::process::Output) {
display("conan install failed with {} \nstdout:\n{} \nstderr:\n{}", o.status, std::str::from_utf8(&o.stdout).unwrap(), std::str::from_utf8(&o.stderr).unwrap())
}
CrackerStorageDifferentUsername(owned_by: String, called_by : String) {
description("Cracker storage owned by different user")
display("Cracker storage owned by: '{}' while you are: '{}'", owned_by, called_by)
}
GitUnableToExtractProjectName(url : String) {
display("unable to extract project name from your url: {}", url)
}
}
}
|
pub struct Instr {
pub instr: Vec<i64>,
pub input: Vec<i64>,
pub output: Vec<i64>,
pub relative_base: i64,
pub instr_ptr: usize,
}
#[derive(Debug)]
pub enum Mode {
Position,
Immediate,
Relative,
}
#[derive(Debug)]
pub enum Opcode {
Add,
Mul,
Inp,
Outp,
Halt,
JmpIfTrue,
JmpIfFalse,
LessThan,
Equals,
ChBase,
}
pub type ModeSet = (Mode, Mode, Mode);
impl Instr {
pub fn iterate(&mut self, amplifier_mode: bool) {
while self.instr_ptr < self.instr.len() {
let opcode = match self.instr[self.instr_ptr] % 100 {
1 => Opcode::Add,
2 => Opcode::Mul,
3 => Opcode::Inp,
4 => Opcode::Outp,
5 => Opcode::JmpIfTrue,
6 => Opcode::JmpIfFalse,
7 => Opcode::LessThan,
8 => Opcode::Equals,
9 => Opcode::ChBase,
99 => Opcode::Halt,
_ => panic!("opcode out of range"),
};
let param_mode: ModeSet = match self.instr[self.instr_ptr] / 100 {
0 => (Mode::Position, Mode::Position, Mode::Position),
1 => (Mode::Immediate, Mode::Position, Mode::Position),
10 => (Mode::Position, Mode::Immediate, Mode::Position),
11 => (Mode::Immediate, Mode::Immediate, Mode::Position),
2 => (Mode::Relative, Mode::Position, Mode::Position),
12 => (Mode::Relative, Mode::Immediate, Mode::Position),
20 => (Mode::Position, Mode::Relative, Mode::Position),
21 => (Mode::Immediate, Mode::Relative, Mode::Position),
22 => (Mode::Relative, Mode::Relative, Mode::Position),
200 => (Mode::Position, Mode::Position, Mode::Relative),
201 => (Mode::Immediate, Mode::Position, Mode::Relative),
210 => (Mode::Position, Mode::Immediate, Mode::Relative),
211 => (Mode::Immediate, Mode::Immediate, Mode::Relative),
202 => (Mode::Relative, Mode::Position, Mode::Relative),
220 => (Mode::Position, Mode::Relative, Mode::Relative),
212 => (Mode::Relative, Mode::Immediate, Mode::Relative),
221 => (Mode::Immediate, Mode::Relative, Mode::Relative),
222 => (Mode::Relative, Mode::Relative, Mode::Relative),
_ => panic!("parameter mode out of range"),
};
//println!("{} {} {:?} {:?}", i, self.instr[i], opcode, param_mode);
match opcode {
Opcode::Add => {
self.add(
self.instr[self.instr_ptr + 1],
self.instr[self.instr_ptr + 2],
self.instr[self.instr_ptr + 3],
¶m_mode,
);
self.instr_ptr += 4
}
Opcode::Mul => {
self.multiply(
self.instr[self.instr_ptr + 1],
self.instr[self.instr_ptr + 2],
self.instr[self.instr_ptr + 3],
¶m_mode,
);
self.instr_ptr += 4;
}
Opcode::Inp => {
self.get_input(
self.instr[(self.instr_ptr + 1) as usize] as usize,
¶m_mode,
);
self.instr_ptr += 2;
}
Opcode::Outp => {
let out =
self.store_output(self.instr[self.instr_ptr + 1] as usize, ¶m_mode);
self.output.push(out);
self.instr_ptr += 2;
if amplifier_mode {
break;
}
}
Opcode::JmpIfTrue => {
let (op1, op2) = self.get_args(
self.instr[self.instr_ptr + 1],
self.instr[self.instr_ptr + 2],
¶m_mode,
);
match op1 == 0 {
false => self.instr_ptr = op2 as usize,
true => self.instr_ptr += 3,
};
}
Opcode::JmpIfFalse => {
let (op1, op2) = self.get_args(
self.instr[self.instr_ptr + 1],
self.instr[self.instr_ptr + 2],
¶m_mode,
);
match op1 != 0 {
false => self.instr_ptr = op2 as usize,
true => self.instr_ptr += 3,
};
}
Opcode::LessThan => {
self.less_than(
self.instr[self.instr_ptr + 1],
self.instr[self.instr_ptr + 2],
self.instr[self.instr_ptr + 3],
¶m_mode,
);
self.instr_ptr += 4;
}
Opcode::Equals => {
self.equals(
self.instr[self.instr_ptr + 1],
self.instr[self.instr_ptr + 2],
self.instr[self.instr_ptr + 3],
¶m_mode,
);
self.instr_ptr += 4;
}
Opcode::ChBase => {
match param_mode.0 {
Mode::Position => {
self.relative_base +=
self.instr[self.instr[self.instr_ptr + 1] as usize]
}
Mode::Immediate => self.relative_base += self.instr[self.instr_ptr + 1],
Mode::Relative => {
self.relative_base += self.instr
[(self.relative_base + self.instr[self.instr_ptr + 1]) as usize]
}
};
//self.relative_base += self.instr[i+1];
self.instr_ptr += 2;
}
Opcode::Halt => break,
};
}
}
fn get_args(&self, inp1: i64, inp2: i64, modes: &ModeSet) -> (i64, i64) {
let op1 = match modes.0 {
Mode::Position => self.instr[inp1 as usize],
Mode::Immediate => inp1,
Mode::Relative => self.instr[(inp1 + self.relative_base) as usize],
};
let op2 = match modes.1 {
Mode::Position => self.instr[inp2 as usize],
Mode::Immediate => inp2,
Mode::Relative => self.instr[(inp2 + self.relative_base) as usize],
};
(op1, op2)
}
fn set_output(&mut self, out: i64, val: i64, modes: &ModeSet) {
// Different from function store_output => this is a helper function that will be used by
// add, multiply, equals, less_than to set output
let out_index = match modes.2 {
Mode::Position => out as usize,
Mode::Relative => (out + self.relative_base) as usize,
Mode::Immediate => panic!("Cannot output in immediate mode"),
};
if out_index > self.instr.len() {
self.instr.resize(out_index * 2, 0);
};
self.instr[out_index] = val;
}
fn less_than(&mut self, inp1: i64, inp2: i64, out: i64, modes: &ModeSet) {
let (op1, op2) = self.get_args(inp1, inp2, modes);
match op1 < op2 {
true => self.set_output(out, 1, modes),
false => self.set_output(out, 0, modes),
};
}
fn equals(&mut self, inp1: i64, inp2: i64, out: i64, modes: &ModeSet) {
let (op1, op2) = self.get_args(inp1, inp2, modes);
match op1 == op2 {
true => self.set_output(out, 1, modes),
false => self.set_output(out, 0, modes),
};
}
fn add(&mut self, inp1: i64, inp2: i64, out: i64, modes: &ModeSet) {
let (op1, op2) = self.get_args(inp1, inp2, modes);
self.set_output(out, op1 + op2, modes);
}
fn multiply(&mut self, inp1: i64, inp2: i64, out: i64, modes: &ModeSet) {
let (op1, op2) = self.get_args(inp1, inp2, modes);
self.set_output(out, op1 * op2, modes);
}
fn get_input(&mut self, pos: usize, modes: &ModeSet) {
let inp_int = self.input.pop().expect("Expected input");
match modes.0 {
Mode::Position => {
self.instr[pos] = inp_int;
}
Mode::Relative => {
self.instr[pos + (self.relative_base as usize)] = inp_int;
}
_ => panic!("Immediate Mode should not exist for input"),
};
}
fn store_output(&mut self, out: usize, modes: &ModeSet) -> i64 {
match modes.0 {
Mode::Position => self.instr[out],
Mode::Immediate => out as i64,
Mode::Relative => self.instr[((out as i64) + self.relative_base) as usize],
}
}
}
|
// Copyright 2014 The Servo Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::ptr::P;
use syntax::codemap::Span;
use syntax::ast::TokenTree;
use syntax::ast;
use syntax::ext::base::{ExtCtxt, MacResult, MacEager};
use syntax::parse::token::{InternedString, Ident, Literal, Lit};
use std::iter::Chain;
use std::collections::HashMap;
use std::ascii::AsciiExt;
fn atom_tok_to_str(t: &TokenTree) -> Option<InternedString> {
Some(match *t {
TokenTree::Token(_, Ident(s, _)) => s.name.as_str(),
TokenTree::Token(_, Literal(Lit::Str_(s), _)) => s.as_str(),
_ => return None,
})
}
// FIXME: libsyntax should provide this (rust-lang/rust#17637)
struct AtomResult {
expr: P<ast::Expr>,
pat: P<ast::Pat>,
}
impl MacResult for AtomResult {
fn make_expr(self: Box<AtomResult>) -> Option<P<ast::Expr>> {
Some(self.expr)
}
fn make_pat(self: Box<AtomResult>) -> Option<P<ast::Pat>> {
Some(self.pat)
}
}
fn make_atom_result(cx: &mut ExtCtxt, name: &str) -> Option<AtomResult> {
let i = match ::string_cache_shared::STATIC_ATOM_SET.get_index_or_hash(name) {
Ok(i) => i,
Err(_hash) => return None,
};
let data = ::string_cache_shared::pack_static(i as u32);
Some(AtomResult {
expr: quote_expr!(&mut *cx, ::string_cache::atom::Atom { data: $data }),
pat: quote_pat!(&mut *cx, ::string_cache::atom::Atom { data: $data }),
})
}
// Translate `atom!(title)` or `atom!("font-weight")` into an `Atom` constant or pattern.
pub fn expand_atom(cx: &mut ExtCtxt, sp: Span, tt: &[TokenTree]) -> Box<MacResult+'static> {
let usage = "Usage: atom!(html) or atom!(\"font-weight\")";
let name = match tt {
[ref t] => ext_expect!(cx, sp, atom_tok_to_str(t), usage),
_ => ext_bail!(cx, sp, usage),
};
box ext_expect!(cx, sp, make_atom_result(cx, &*name),
&format!("Unknown static atom {}", &*name))
}
// Translate `ns!(HTML)` into `Namespace { atom: atom!("http://www.w3.org/1999/xhtml") }`.
// The argument is ASCII-case-insensitive.
pub fn expand_ns(cx: &mut ExtCtxt, sp: Span, tt: &[TokenTree]) -> Box<MacResult+'static> {
use string_cache_shared::ALL_NS;
fn usage() -> String {
let ns_names: Vec<&'static str> = ALL_NS[1..].iter()
.map(|&(x, _)| x).collect();
format!("Usage: ns!(HTML), case-insensitive. \
Known namespaces: {}",
ns_names.join(" "))
}
let name = ext_expect!(cx, sp, match tt {
[ref t] => atom_tok_to_str(t),
_ => None,
}, &usage());
let &(_, url) = ext_expect!(cx, sp,
ALL_NS.iter().find(|&&(short, _)| short.eq_ignore_ascii_case(&*name)),
&usage());
// All of the URLs should be in the static atom table.
let AtomResult { expr, pat } = ext_expect!(cx, sp, make_atom_result(cx, url),
&format!("internal plugin error: can't find namespace url {}", url));
box AtomResult {
expr: quote_expr!(&mut *cx, ::string_cache::namespace::Namespace($expr)),
pat: quote_pat!(&mut *cx, ::string_cache::namespace::Namespace($pat)),
}
}
|
use utopia_core::{
math::{Size, Vector2},
widgets::{pod::WidgetPod, TypedWidget, Widget},
Backend, BoxConstraints, CommonPrimitive,
};
use super::scrollable::{Scrollable, ScrollableState};
pub struct ScrollView<T, B: Backend> {
scroll: Scrollable<T, B>,
scrollable_state: ScrollableState,
vertical: Option<WidgetPod<ScrollableState, B>>,
horizontal: Option<WidgetPod<ScrollableState, B>>,
}
impl<T, B: Backend> ScrollView<T, B> {
pub fn new<TW: TypedWidget<T, B> + 'static>(child: TW) -> Self {
let scrollable_state = ScrollableState::default();
let scroll = Scrollable::new(child);
ScrollView {
scroll,
vertical: None,
horizontal: None,
scrollable_state: scrollable_state,
}
}
pub fn horizontal(mut self, horizontal: WidgetPod<ScrollableState, B>) -> Self {
self.horizontal = Some(horizontal);
self
}
pub fn vertical(mut self, vertical: WidgetPod<ScrollableState, B>) -> Self {
self.vertical = Some(vertical);
self
}
}
impl<T, B: Backend> Widget<T> for ScrollView<T, B>
where
Scrollable<T, B>: TypedWidget<T, B>,
B::Primitive: From<CommonPrimitive<B::Primitive>>,
B::Event: Clone,
{
type Primitive = CommonPrimitive<B::Primitive>;
type Context = B;
type Event = B::Event;
type Reaction = B::EventReaction;
fn layout(&mut self, bc: &BoxConstraints, context: &Self::Context, data: &T) -> Size {
let size = TypedWidget::<T, B>::layout(&mut self.scroll, bc, context, data);
self.scroll.state = self.scrollable_state.clone();
let scrollable_state = &self.scrollable_state;
if let Some(vertical) = self.vertical.as_mut() {
let bc = bc.loosen();
let bar_size =
TypedWidget::<ScrollableState, B>::layout(vertical, &bc, context, scrollable_state);
vertical.set_origin(Vector2::new(size.width - bar_size.width, 0.));
}
if let Some(horizontal) = self.horizontal.as_mut() {
let bc = bc.loosen();
let bar_size = TypedWidget::<ScrollableState, B>::layout(
horizontal,
&bc,
context,
scrollable_state,
);
horizontal.set_origin(Vector2::new(0., size.height - bar_size.height));
}
Size {
width: size.width,
height: size.height,
}
}
fn draw(&self, origin: Vector2, size: Size, data: &T) -> Self::Primitive {
let scroll = TypedWidget::<T, B>::draw(&self.scroll, origin, size, data);
let vertical = self
.vertical
.as_ref()
.map(|vertical| {
TypedWidget::<ScrollableState, B>::draw(
vertical,
origin,
size,
&self.scrollable_state,
)
.into()
})
.unwrap_or_else(|| CommonPrimitive::<B::Primitive>::None);
let horizontal = self
.horizontal
.as_ref()
.map(|horizontal| {
TypedWidget::<ScrollableState, B>::draw(
horizontal,
origin,
size,
&self.scrollable_state,
)
.into()
})
.unwrap_or_else(|| CommonPrimitive::<B::Primitive>::None);
CommonPrimitive::Group {
children: vec![scroll, vertical.into(), horizontal.into()],
}
}
fn event(
&mut self,
origin: Vector2,
size: Size,
data: &mut T,
event: Self::Event,
) -> Option<Self::Reaction> {
if let Some(horizontal) = self.horizontal.as_mut() {
if let Some(reaction) = TypedWidget::<ScrollableState, B>::event(
horizontal,
origin,
size,
&mut self.scrollable_state,
event.clone(),
) {
return Some(reaction);
}
}
if let Some(vertical) = self.vertical.as_mut() {
if let Some(reaction) = TypedWidget::<ScrollableState, B>::event(
vertical,
origin,
size,
&mut self.scrollable_state,
event.clone(),
) {
return Some(reaction);
}
}
TypedWidget::<T, B>::event(&mut self.scroll, origin, size, data, event)
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
failure::{Error, ResultExt},
fidl_fuchsia_test_hub as fhub, fuchsia_async as fasync,
fuchsia_component::client::connect_to_service,
};
macro_rules! get_names_from_listing {
($dir_listing:ident) => {
&mut $dir_listing.iter().map(|entry| &entry.name as &str)
};
}
async fn report_directory_contents(
hub_report: &fhub::HubReportProxy,
dir_path: &str,
) -> Result<(), Error> {
let dir_proxy = io_util::open_directory_in_namespace(dir_path, io_util::OPEN_RIGHT_READABLE)
.expect("Unable to open directory in namespace");
let dir_listing = files_async::readdir(&dir_proxy).await.expect("readdir failed");
hub_report
.list_directory(dir_path, get_names_from_listing!(dir_listing))
.await
.context("list directory failed")?;
Ok(())
}
#[fasync::run_singlethreaded]
async fn main() -> Result<(), Error> {
let hub_report =
connect_to_service::<fhub::HubReportMarker>().context("error connecting to HubReport")?;
// Read the children of this component and pass the results to the integration test
// via HubReport.
report_directory_contents(&hub_report, "/hub/children").await?;
// Read the hub of the child and pass the results to the integration test
// via HubReport
report_directory_contents(&hub_report, "/hub/children/child").await?;
// Read the grandchildren and pass the results to the integration test
// via HubReport
report_directory_contents(&hub_report, "/hub/children/child/children").await?;
Ok(())
}
|
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use executor::Executor;
use executor_types::ExecutedTrees;
use libra_config::config::NodeConfig;
use libra_crypto::{
ed25519::{Ed25519PrivateKey, Ed25519PublicKey},
HashValue, PrivateKey, Uniform,
};
use libra_types::{
account_address::AccountAddress,
account_config,
account_state::AccountState,
block_info::BlockInfo,
block_metadata::BlockMetadata,
discovery_set::DiscoverySet,
ledger_info::{LedgerInfo, LedgerInfoWithSignatures},
transaction::Transaction,
validator_config::ValidatorConfig,
validator_set::ValidatorSet,
};
use libra_vm::LibraVM;
use libradb::{LibraDB, LibraDBTrait};
use rand::{rngs::StdRng, SeedableRng};
use std::{collections::BTreeMap, convert::TryFrom, sync::Arc};
use storage_client::{StorageReadServiceClient, StorageWriteServiceClient};
use tokio::runtime::Runtime;
struct Node {
account: AccountAddress,
executor: Arc<Executor<LibraVM>>,
storage: Arc<LibraDB>,
_storage_service: Runtime,
}
fn setup(config: &NodeConfig) -> Node {
let storage = storage_service::init_libra_db(config);
let storage_service = storage_service::start_storage_service_with_db(&config, storage.clone());
let executor = Arc::new(Executor::new(
Arc::new(StorageReadServiceClient::new(&config.storage.address)),
Arc::new(StorageWriteServiceClient::new(&config.storage.address)),
config,
));
Node {
account: config.validator_network.as_ref().unwrap().peer_id,
executor,
storage,
_storage_service: storage_service,
}
}
fn get_discovery_set(storage: &Arc<LibraDB>) -> DiscoverySet {
let account = account_config::discovery_set_address();
let blob = storage.get_latest_account_state(account).unwrap().unwrap();
let account_state = AccountState::try_from(&blob).unwrap();
account_state
.get_discovery_set_resource()
.unwrap()
.unwrap()
.discovery_set()
.clone()
}
fn get_validator_config(storage: &Arc<LibraDB>, account: AccountAddress) -> ValidatorConfig {
let blob = storage.get_latest_account_state(account).unwrap().unwrap();
let account_state = AccountState::try_from(&blob).unwrap();
account_state
.get_validator_config_resource()
.unwrap()
.unwrap()
.validator_config
}
fn get_validator_set(storage: &Arc<LibraDB>) -> ValidatorSet<Ed25519PublicKey> {
let account = account_config::validator_set_address();
let blob = storage.get_latest_account_state(account).unwrap().unwrap();
let account_state = AccountState::try_from(&blob).unwrap();
account_state
.get_validator_set_resource()
.unwrap()
.unwrap()
.validator_set()
.clone()
}
fn execute_and_commit(node: &Node, mut block: Vec<Transaction>) {
let block_id = HashValue::zero();
let startup_info = node.storage.get_startup_info().unwrap().unwrap();
let clock = startup_info.committed_tree_state.version + 1;
let committed_trees = ExecutedTrees::from(startup_info.committed_tree_state);
// This will set the current clock to be equal to the current version + 1, this guarantees that
// the clock is always refreshed for this set of transactions.
let block_metadata = BlockMetadata::new(block_id, clock, BTreeMap::new(), node.account);
let prologue = Transaction::BlockMetadata(block_metadata);
block.insert(0, prologue);
let output = node
.executor
.execute_block(block_id, block.clone(), &committed_trees, &committed_trees)
.unwrap();
let root_hash = output.accu_root();
let version = output.version().unwrap();
let ledger_info = LedgerInfo::new(
BlockInfo::new(0, 0, block_id, root_hash, version, 0, None),
HashValue::zero(),
);
let ledger_info_with_sigs = LedgerInfoWithSignatures::new(ledger_info, BTreeMap::new());
let executed_block = vec![(block, Arc::new(output))];
node.executor
.commit_blocks(executed_block, ledger_info_with_sigs, &committed_trees)
.unwrap();
}
#[test]
// This simple test just proves that genesis took effect and the values are in storage
fn test() {
let (config, _genesis_key) = config_builder::test_config();
let node = setup(&config);
get_discovery_set(&node.storage);
get_validator_config(&node.storage, node.account);
get_validator_set(&node.storage);
}
#[test]
// This test verifies that a node can rotate its key and it results in a new validator set
fn test_consensus_rotation() {
let (config, _genesis_key) = config_builder::test_config();
let node = setup(&config);
let test_config = config.test.unwrap();
let mut keypair = test_config.consensus_keypair.unwrap();
let genesis_prikey = keypair.take_private().unwrap();
let genesis_pubkey = genesis_prikey.public_key();
let account_prikey = test_config.account_keypair.unwrap().take_private().unwrap();
let genesis_config = get_validator_config(&node.storage, node.account);
let genesis_set = get_validator_set(&node.storage);
assert_eq!(genesis_pubkey, genesis_config.consensus_pubkey);
assert_eq!(&genesis_pubkey, genesis_set[0].consensus_public_key());
assert_eq!(&node.account, genesis_set[0].account_address());
let mut rng = StdRng::from_seed([44u8; 32]);
let new_prikey = Ed25519PrivateKey::generate_for_testing(&mut rng);
let new_pubkey = new_prikey.public_key();
let txn = crate::build_transaction(node.account, 0, &account_prikey, &new_pubkey);
execute_and_commit(&node, vec![txn]);
let new_config = get_validator_config(&node.storage, node.account);
let new_set = get_validator_set(&node.storage);
assert!(new_pubkey != genesis_pubkey);
assert_eq!(new_pubkey, new_config.consensus_pubkey);
assert_eq!(&new_pubkey, new_set[0].consensus_public_key());
}
|
use std::fmt::{Formatter, Display, Result};
#[derive(Debug)]
struct Color{
r: i32,
g: i32,
b: i32
}
impl Display for Color {
fn fmt(&self, f: &mut Formatter) -> Result {
let r = &self.r;
let g = &self.g;
let b = &self.b;
write!(f, "RGB ({r},{g},{b}) 0x{r:0>2X}{g:0>2X}{b:0>2X}")
}
}
fn main(){
let colors = [
Color {r:128,g:255,b:90},
Color {r:0,g:3,b:254},
Color {r:0,g:0,b:0}
];
for color in colors.iter() {
println!("{color}");
}
} |
use crate::decode::Decode;
use crate::encode::Encode;
use crate::postgres::protocol::TypeId;
use crate::postgres::{PgData, PgRawBuffer, PgTypeInfo, PgValue, Postgres};
use crate::types::Type;
impl Type<Postgres> for [u8] {
fn type_info() -> PgTypeInfo {
PgTypeInfo::new(TypeId::BYTEA, "BYTEA")
}
}
impl Type<Postgres> for [&'_ [u8]] {
fn type_info() -> PgTypeInfo {
PgTypeInfo::new(TypeId::ARRAY_BYTEA, "BYTEA[]")
}
}
impl Type<Postgres> for Vec<&'_ [u8]> {
fn type_info() -> PgTypeInfo {
<&'_ [u8] as Type<Postgres>>::type_info()
}
}
impl Type<Postgres> for Vec<u8> {
fn type_info() -> PgTypeInfo {
<[u8] as Type<Postgres>>::type_info()
}
}
impl Encode<Postgres> for [u8] {
fn encode(&self, buf: &mut PgRawBuffer) {
buf.extend_from_slice(self);
}
}
impl Encode<Postgres> for Vec<u8> {
fn encode(&self, buf: &mut PgRawBuffer) {
<[u8] as Encode<Postgres>>::encode(self, buf);
}
}
impl<'de> Decode<'de, Postgres> for Vec<u8> {
fn decode(value: PgValue<'de>) -> crate::Result<Self> {
match value.try_get()? {
PgData::Binary(buf) => Ok(buf.to_vec()),
PgData::Text(s) => {
// BYTEA is formatted as \x followed by hex characters
hex::decode(&s[2..]).map_err(crate::Error::decode)
}
}
}
}
impl<'de> Decode<'de, Postgres> for &'de [u8] {
fn decode(value: PgValue<'de>) -> crate::Result<Self> {
match value.try_get()? {
PgData::Binary(buf) => Ok(buf),
PgData::Text(_s) => Err(crate::Error::Decode(
"unsupported decode to `&[u8]` of BYTEA in a simple query; \
use a prepared query or decode to `Vec<u8>`"
.into(),
)),
}
}
}
|
//! Write an algorithm such that if an element in an
//! M x N matrix is 0 it's entire row and column
//! are set to 0
type Matrix = Vec<Vec<u32>>;
pub fn zero_matrix(m: &mut Matrix) {
let mut rows = vec![false; m.len()];
let mut cols = vec![false; m[0].len()];
for (i, row) in m.iter().enumerate() {
for (j, val) in row.iter().enumerate() {
if *val == 0 {
rows[i] = true;
cols[j] = true;
}
}
}
for i in 0..rows.len() {
if rows[i] {
zero_row(m, i);
}
}
for i in 0..cols.len() {
if cols[i] {
zero_col(m, i);
}
}
}
fn zero_row(m: &mut Matrix, row: usize) {
for i in 0..m[row].len() {
m[row][i] = 0;
}
}
fn zero_col(m: &mut Matrix, col: usize) {
for i in 0..m.len() {
m[i][col] = 0;
}
}
#[cfg(test)]
mod test_zero_matrix {
use super::*;
#[test]
fn test_ok() {
let mut matrix: Matrix = vec![
vec![0, 1, 0],
vec![2, 3, 4],
];
let expected: Matrix = vec![
vec![0, 0, 0],
vec![0, 3, 0],
];
zero_matrix(&mut matrix);
assert_eq!(matrix, expected);
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Key register"]
pub kr: KR,
#[doc = "0x04 - Prescaler register"]
pub pr: PR,
#[doc = "0x08 - Reload register"]
pub rlr: RLR,
#[doc = "0x0c - Status register"]
pub sr: SR,
#[doc = "0x10 - Window register"]
pub winr: WINR,
_reserved5: [u8; 988usize],
#[doc = "0x3f0 - hardware configuration register"]
pub hwcfgr: HWCFGR,
#[doc = "0x3f4 - EXTI IP Version register"]
pub verr: VERR,
#[doc = "0x3f8 - EXTI Identification register"]
pub ipidr: IPIDR,
#[doc = "0x3fc - EXTI Size ID register"]
pub sidr: SIDR,
}
#[doc = "Key register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [kr](kr) module"]
pub type KR = crate::Reg<u32, _KR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _KR;
#[doc = "`write(|w| ..)` method takes [kr::W](kr::W) writer structure"]
impl crate::Writable for KR {}
#[doc = "Key register"]
pub mod kr;
#[doc = "Prescaler register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pr](pr) module"]
pub type PR = crate::Reg<u32, _PR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PR;
#[doc = "`read()` method returns [pr::R](pr::R) reader structure"]
impl crate::Readable for PR {}
#[doc = "`write(|w| ..)` method takes [pr::W](pr::W) writer structure"]
impl crate::Writable for PR {}
#[doc = "Prescaler register"]
pub mod pr;
#[doc = "Reload register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rlr](rlr) module"]
pub type RLR = crate::Reg<u32, _RLR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RLR;
#[doc = "`read()` method returns [rlr::R](rlr::R) reader structure"]
impl crate::Readable for RLR {}
#[doc = "`write(|w| ..)` method takes [rlr::W](rlr::W) writer structure"]
impl crate::Writable for RLR {}
#[doc = "Reload register"]
pub mod rlr;
#[doc = "Status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sr](sr) module"]
pub type SR = crate::Reg<u32, _SR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SR;
#[doc = "`read()` method returns [sr::R](sr::R) reader structure"]
impl crate::Readable for SR {}
#[doc = "Status register"]
pub mod sr;
#[doc = "Window register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [winr](winr) module"]
pub type WINR = crate::Reg<u32, _WINR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WINR;
#[doc = "`read()` method returns [winr::R](winr::R) reader structure"]
impl crate::Readable for WINR {}
#[doc = "`write(|w| ..)` method takes [winr::W](winr::W) writer structure"]
impl crate::Writable for WINR {}
#[doc = "Window register"]
pub mod winr;
#[doc = "hardware configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [hwcfgr](hwcfgr) module"]
pub type HWCFGR = crate::Reg<u32, _HWCFGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _HWCFGR;
#[doc = "`read()` method returns [hwcfgr::R](hwcfgr::R) reader structure"]
impl crate::Readable for HWCFGR {}
#[doc = "`write(|w| ..)` method takes [hwcfgr::W](hwcfgr::W) writer structure"]
impl crate::Writable for HWCFGR {}
#[doc = "hardware configuration register"]
pub mod hwcfgr;
#[doc = "EXTI IP Version register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [verr](verr) module"]
pub type VERR = crate::Reg<u32, _VERR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VERR;
#[doc = "`read()` method returns [verr::R](verr::R) reader structure"]
impl crate::Readable for VERR {}
#[doc = "EXTI IP Version register"]
pub mod verr;
#[doc = "EXTI Identification register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ipidr](ipidr) module"]
pub type IPIDR = crate::Reg<u32, _IPIDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IPIDR;
#[doc = "`read()` method returns [ipidr::R](ipidr::R) reader structure"]
impl crate::Readable for IPIDR {}
#[doc = "EXTI Identification register"]
pub mod ipidr;
#[doc = "EXTI Size ID register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sidr](sidr) module"]
pub type SIDR = crate::Reg<u32, _SIDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SIDR;
#[doc = "`read()` method returns [sidr::R](sidr::R) reader structure"]
impl crate::Readable for SIDR {}
#[doc = "EXTI Size ID register"]
pub mod sidr;
|
#[prelude_import]
use ::std::prelude::v1::*; /* node_id: 3 hir local_id: 0 */
#[macro_use]
extern crate std; /* node_id: 9 hir local_id: 0 */
fn main() ({
((<Person>::new /* node_id: 15 hir local_id: 5
*/)(("not_bind" /* node_id: 16 hir local_id: 6 */),
(18 /* node_id: 17 hir local_id: 7 */)) /*
node_id: 18 hir local_id: 8 */);
let kiske /* pat node_id: 20 hir local_id: 10 */ =
((<Person>::new /* node_id: 23 hir local_id: 14
*/)(("kiske" /* node_id: 24 hir local_id: 15 */),
(18 /* node_id: 25 hir local_id: 16 */)) /*
node_id: 26 hir local_id: 17 */);
} /* block node_id: 12 hir local_id: 19 */ /*
node_id: 67 hir local_id: 20 */) /* node_id: 10 hir local_id: 0
*/
struct Person {
pub name: String,
pub age: u32,
} /* node_id: 27 hir local_id: 0 */
impl Person {
fn new(name /* pat node_id: 43 hir local_id: 14 */: &str,
age /* pat node_id: 48 hir local_id: 16 */: u32)
->
Person ({
(Person{name:
((name /* node_id: 57 hir local_id: 5
*/).to_string() /*
node_id: 58 hir local_id: 6 */),
(age /* node_id: 60 hir local_id: 9 */),} /*
node_id: 61 hir local_id: 10 */)
} /* block node_id: 53 hir local_id: 11 */ /*
node_id: 70 hir local_id: 12 */)
/*
40
*/
} /* node_id: 36 hir local_id: 0 */
|
//! Wrapper around the `fetch` API.
//!
//! # Example
//!
//! ```
//! # use reqwasm::http::Request;
//! # async fn no_run() {
//! let resp = Request::get("/path")
//! .send()
//! .await
//! .unwrap();
//! assert_eq!(resp.status(), 200);
//! # }
//! ```
use crate::{js_to_error, Error};
use serde::de::DeserializeOwned;
use std::fmt;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use web_sys::window;
pub use web_sys::{
AbortSignal, FormData, Headers, ObserverCallback, ReadableStream, ReferrerPolicy, RequestCache,
RequestCredentials, RequestMode, RequestRedirect,
};
#[allow(
missing_docs,
missing_debug_implementations,
clippy::upper_case_acronyms
)]
/// Valid request methods.
#[derive(Clone, Copy, Debug)]
pub enum Method {
GET,
HEAD,
POST,
PUT,
DELETE,
CONNECT,
OPTIONS,
TRACE,
PATCH,
}
impl fmt::Display for Method {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Method::GET => "GET",
Method::HEAD => "HEAD",
Method::POST => "POST",
Method::PUT => "PUT",
Method::DELETE => "DELETE",
Method::CONNECT => "CONNECT",
Method::OPTIONS => "OPTIONS",
Method::TRACE => "TRACE",
Method::PATCH => "PATCH",
};
write!(f, "{}", s)
}
}
/// A request.
pub struct Request {
options: web_sys::RequestInit,
headers: web_sys::Headers,
url: String,
}
impl Request {
/// Creates a new request with a url.
pub fn new(url: &str) -> Self {
Self {
options: web_sys::RequestInit::new(),
headers: web_sys::Headers::new().expect("headers"),
url: url.into(),
}
}
/// Sets the body.
pub fn body(mut self, body: impl Into<JsValue>) -> Self {
self.options.body(Some(&body.into()));
self
}
/// Sets the request cache.
pub fn cache(mut self, cache: RequestCache) -> Self {
self.options.cache(cache);
self
}
/// Sets the request credentials.
pub fn credentials(mut self, credentials: RequestCredentials) -> Self {
self.options.credentials(credentials);
self
}
/// Sets a header.
pub fn header(self, key: &str, value: &str) -> Self {
self.headers.set(key, value).expect("set header");
self
}
/// Sets the request integrity.
pub fn integrity(mut self, integrity: &str) -> Self {
self.options.integrity(integrity);
self
}
/// Sets the request method.
pub fn method(mut self, method: Method) -> Self {
self.options.method(&method.to_string());
self
}
/// Sets the request mode.
pub fn mode(mut self, mode: RequestMode) -> Self {
self.options.mode(mode);
self
}
/// Sets the observer callback.
pub fn observe(mut self, observe: &ObserverCallback) -> Self {
self.options.observe(observe);
self
}
/// Sets the request redirect.
pub fn redirect(mut self, redirect: RequestRedirect) -> Self {
self.options.redirect(redirect);
self
}
/// Sets the request referrer.
pub fn referrer(mut self, referrer: &str) -> Self {
self.options.referrer(referrer);
self
}
/// Sets the request referrer policy.
pub fn referrer_policy(mut self, referrer_policy: ReferrerPolicy) -> Self {
self.options.referrer_policy(referrer_policy);
self
}
/// Sets the request abort signal.
pub fn abort_signal(mut self, signal: Option<&AbortSignal>) -> Self {
self.options.signal(signal);
self
}
/// Executes the request.
pub async fn send(mut self) -> Result<Response, Error> {
self.options.headers(&self.headers);
let request = web_sys::Request::new_with_str_and_init(&self.url, &self.options)
.map_err(js_to_error)?;
let promise = window().unwrap().fetch_with_request(&request);
let response = JsFuture::from(promise).await.map_err(js_to_error)?;
match response.dyn_into::<web_sys::Response>() {
Ok(response) => Ok(Response {
response: response.unchecked_into(),
}),
Err(_) => Err(Error::Other(anyhow::anyhow!("can't convert to Response"))),
}
}
/// Creates a new [`GET`][Method::GET] `Request` with url.
pub fn get(url: &str) -> Self {
Self::new(url).method(Method::GET)
}
/// Creates a new [`POST`][Method::POST] `Request` with url.
pub fn post(url: &str) -> Self {
Self::new(url).method(Method::POST)
}
/// Creates a new [`PUT`][Method::PUT] `Request` with url.
pub fn put(url: &str) -> Self {
Self::new(url).method(Method::PUT)
}
/// Creates a new [`DELETE`][Method::DELETE] `Request` with url.
pub fn delete(url: &str) -> Self {
Self::new(url).method(Method::DELETE)
}
/// Creates a new [`PATCH`][Method::PATCH] `Request` with url.
pub fn patch(url: &str) -> Self {
Self::new(url).method(Method::PATCH)
}
}
impl fmt::Debug for Request {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Request").field("url", &self.url).finish()
}
}
/// The [`Request`]'s response
pub struct Response {
response: web_sys::Response,
}
impl Response {
/// Gets the url.
pub fn url(&self) -> String {
self.response.url()
}
/// Whether the request was redirected.
pub fn redirected(&self) -> bool {
self.response.redirected()
}
/// Gets the status.
pub fn status(&self) -> u16 {
self.response.status()
}
/// Whether the response was `ok`.
pub fn ok(&self) -> bool {
self.response.ok()
}
/// Gets the status text.
pub fn status_text(&self) -> String {
self.response.status_text()
}
/// Gets the headers.
pub fn headers(&self) -> Headers {
self.response.headers()
}
/// Whether the body was used.
pub fn body_used(&self) -> bool {
self.response.body_used()
}
/// Gets the body.
pub fn body(&self) -> Option<ReadableStream> {
self.response.body()
}
/// Gets the raw [`Response`][web_sys::Response] object.
pub fn as_raw(&self) -> &web_sys::Response {
&self.response
}
/// Gets the form data.
pub async fn form_data(&self) -> Result<FormData, Error> {
let promise = self.response.form_data().map_err(js_to_error)?;
let val = JsFuture::from(promise).await.map_err(js_to_error)?;
Ok(FormData::from(val))
}
/// Gets and parses the json.
pub async fn json<T: DeserializeOwned>(&self) -> Result<T, Error> {
let promise = self.response.json().map_err(js_to_error)?;
let json = JsFuture::from(promise).await.map_err(js_to_error)?;
Ok(json.into_serde()?)
}
/// Gets the response text.
pub async fn text(&self) -> Result<String, Error> {
let promise = self.response.text().unwrap();
let val = JsFuture::from(promise).await.map_err(js_to_error)?;
let string = js_sys::JsString::from(val);
Ok(String::from(&string))
}
}
impl fmt::Debug for Response {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Response")
.field("url", &self.url())
.field("redirected", &self.redirected())
.field("status", &self.status())
.field("headers", &self.headers())
.field("body_used", &self.body_used())
.finish()
}
}
|
use std::sync::{Arc, Mutex};
use std::task::Waker;
use waker_fn::waker_fn;
use futures_lit::pin;
use crossbeam::sync::Parker;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll}:
pub struct SpawnBlocking<T>(Arc<Mutex<Shared<T>>>);
// The Shared struct serves as a rendezvous between the future and the thread running the closure
// Polling the future checks whether 'value' is present and saves the waker in 'waker' if not
// The thread running the closure saves its return value in 'value' and then invokes 'waker', if present.
struct Shared<T> {
value: Option<T>,
waker: Option<Waker>,
}
pub fn spawn_blocking<T,F>(closure: F) -> SpawnBlocking<T>
where F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
{
let inner = Arc::new(Mutex::new(Shared {
value: None,
waker: None,
}));
std::thread::spawn({
let inner = inner.clone();
move || {
let value = closure(); // run the closure to get the value
let maybe_waker = {
let mut guard = inner.lock().unwrap(); // unlock the mutex
guard.value = Some(value); // set the 'value'
guard.waker.take() // move the 'waker' into 'maybe_waker'
};
if let Some(waker) = maybe_waker { // if there is a waker, consume the waker with '.wake()'
waker.wake();
}
}
});
SpawnBlocking(inner)
}
impl<T: Send> Future for SpawnBlocking<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
let mut guard = self.0.lock().unwrap();
if let Some(value) = guard.value.take() {
return Poll::Ready(value);
}
guard.waker = Some(cx.waker().clone());
Poll::Pending
}
}
fn block_con<F: Future>(future: F) -> F::Output {
let parker = Parker::new(); // Parker is a blocking primitive that blocks the thread until someone else calls '.unpark()' on the corresponding Unparker
let unparker = parker.unparker().clone(); // unparker will unblock the parked thread
let waker = waker_fn(move || unparker.unpark());
let mut context = Context::from_waker(&waker);
pin!(future); // 'pin!' macro takes ownership of the future and declares a new variable fo the same name whose type is 'Pin<&mut F>' and that borrows the future.
// This type is needed by the poll method
loop {
match future.as_mut().poll(&mut context) {
Poll::Ready(value) => return value,
Poll::Pending => parker.park(),
}
}
}
|
use seed::{*, prelude::*};
use crate::{
components::navbar,
containers::{favorites, login, search},
router::Route,
state::{Model, ModelEvent},
};
/// The root application view.
pub fn app(model: &Model) -> Vec<Node<ModelEvent>> {
let route = &model.route;
let nav = if route != &Route::Init && route != &Route::Login {
navbar(model)
} else {
div!()
};
vec![
section!(attrs!{At::Class => "hero is-success is-fullheight"},
nav,
match &model.route {
Route::Init => div!(),
Route::Login => login(model),
Route::Search => search(model),
Route::Favorites => favorites(model),
}
)
]
}
|
use actix_web::web;
use futures::Future;
use survey_manager_core::app_services::commands::SurveyCommands;
use domain_patterns::command::Handles;
use crate::generate;
use crate::error::ApiError;
pub fn handle_command_async(
cmd: SurveyCommands,
) -> impl Future<Item = String, Error = ApiError> {
web::block(move || generate::command_handler().handle(cmd) )
.from_err()
}
|
use magnesium::*;
#[test]
fn test_parsing() {
let xml = r#"
<?xml version="1.0" encoding="UTF-8"?>
<registry>
<!-- We're gonna pretend that there's a whole file here -->
<types>
<type>typedef unsigned int <name>GraphicsEnum</name>;</type>
</types>
<enums group="GraphicPolygons">
<enum name="GRAPHIC_POINTS" value="0x0000" />
<enum name="GRAPHIC_LINES" value="0x0001" />
</enums>
</registry>
"#;
let mut iter = ElementIterator::new(xml);
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "registry", attrs: "" })
);
assert_eq!(iter.next(), Some(XmlElement::Text("\n ")));
assert_eq!(
iter.next(),
Some(XmlElement::Comment(
" We're gonna pretend that there's a whole file here "
))
);
assert_eq!(iter.next(), Some(XmlElement::Text("\n ")));
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "types", attrs: "" })
);
assert_eq!(iter.next(), Some(XmlElement::Text("\n ")));
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "type", attrs: "" })
);
assert_eq!(iter.next(), Some(XmlElement::Text("typedef unsigned int ")));
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "name", attrs: "" })
);
assert_eq!(iter.next(), Some(XmlElement::Text("GraphicsEnum")));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "name" }));
assert_eq!(iter.next(), Some(XmlElement::Text(";")));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "type" }));
assert_eq!(iter.next(), Some(XmlElement::Text("\n ")));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "types" }));
assert_eq!(iter.next(), Some(XmlElement::Text("\n ")));
//
assert_eq!(
iter.next(),
Some(XmlElement::StartTag {
name: "enums",
attrs: r#"group="GraphicPolygons""#
})
);
assert_eq!(iter.next(), Some(XmlElement::Text("\n ")));
assert_eq!(
iter.next(),
Some(XmlElement::EmptyTag {
name: "enum",
attrs: r#"name="GRAPHIC_POINTS" value="0x0000" "#
})
);
assert_eq!(iter.next(), Some(XmlElement::Text("\n ")));
assert_eq!(
iter.next(),
Some(XmlElement::EmptyTag {
name: "enum",
attrs: r#"name="GRAPHIC_LINES" value="0x0001" "#
})
);
assert_eq!(iter.next(), Some(XmlElement::Text("\n ")));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "enums" }));
assert_eq!(iter.next(), Some(XmlElement::Text("\n ")));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "registry" }));
assert_eq!(iter.next(), None);
}
#[test]
fn test_whitespace_skipping_parsing() {
let xml = r#"
<?xml version="1.0" encoding="UTF-8"?>
<registry>
<!-- We're gonna pretend that there's a whole file here -->
<types>
<type>typedef unsigned int <name>GraphicsEnum</name>;</type>
</types>
<enums group="GraphicPolygons">
<enum name="GRAPHIC_POINTS" value="0x0000" />
<enum name="GRAPHIC_LINES" value="0x0001" />
</enums>
</registry>
"#;
let mut iter = ElementIterator::new(xml).filter_map(skip_empty_text_elements);
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "registry", attrs: "" })
);
assert_eq!(
iter.next(),
Some(XmlElement::Comment(
" We're gonna pretend that there's a whole file here "
))
);
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "types", attrs: "" })
);
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "type", attrs: "" })
);
assert_eq!(iter.next(), Some(XmlElement::Text("typedef unsigned int ")));
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "name", attrs: "" })
);
assert_eq!(iter.next(), Some(XmlElement::Text("GraphicsEnum")));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "name" }));
assert_eq!(iter.next(), Some(XmlElement::Text(";")));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "type" }));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "types" }));
assert_eq!(
iter.next(),
Some(XmlElement::StartTag {
name: "enums",
attrs: r#"group="GraphicPolygons""#
})
);
assert_eq!(
iter.next(),
Some(XmlElement::EmptyTag {
name: "enum",
attrs: r#"name="GRAPHIC_POINTS" value="0x0000" "#
})
);
assert_eq!(
iter.next(),
Some(XmlElement::EmptyTag {
name: "enum",
attrs: r#"name="GRAPHIC_LINES" value="0x0001" "#
})
);
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "enums" }));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "registry" }));
assert_eq!(iter.next(), None);
}
#[test]
fn test_skipping_comments_parsing() {
let xml = r#"
<?xml version="1.0" encoding="UTF-8"?>
<registry>
<!-- We're gonna pretend that there's a whole file here -->
<types>
<type>typedef unsigned int <name>GraphicsEnum</name>;</type>
</types>
<enums group="GraphicPolygons">
<enum name="GRAPHIC_POINTS" value="0x0000" />
<enum name="GRAPHIC_LINES" value="0x0001" />
</enums>
</registry>
"#;
let mut iter = ElementIterator::new(xml)
.filter_map(skip_empty_text_elements)
.filter_map(skip_comments);
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "registry", attrs: "" })
);
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "types", attrs: "" })
);
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "type", attrs: "" })
);
assert_eq!(iter.next(), Some(XmlElement::Text("typedef unsigned int ")));
assert_eq!(
iter.next(),
Some(XmlElement::StartTag { name: "name", attrs: "" })
);
assert_eq!(iter.next(), Some(XmlElement::Text("GraphicsEnum")));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "name" }));
assert_eq!(iter.next(), Some(XmlElement::Text(";")));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "type" }));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "types" }));
assert_eq!(
iter.next(),
Some(XmlElement::StartTag {
name: "enums",
attrs: r#"group="GraphicPolygons""#
})
);
assert_eq!(
iter.next(),
Some(XmlElement::EmptyTag {
name: "enum",
attrs: r#"name="GRAPHIC_POINTS" value="0x0000" "#
})
);
assert_eq!(
iter.next(),
Some(XmlElement::EmptyTag {
name: "enum",
attrs: r#"name="GRAPHIC_LINES" value="0x0001" "#
})
);
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "enums" }));
assert_eq!(iter.next(), Some(XmlElement::EndTag { name: "registry" }));
assert_eq!(iter.next(), None);
}
#[test]
fn test_empty_tag_no_attrs() {
let xml = "<apientry/>";
let mut iter = ElementIterator::new(xml);
assert_eq!(
iter.next(),
Some(XmlElement::EmptyTag { name: "apientry", attrs: "" })
);
}
|
use libc::{getpriority, PRIO_PROCESS, getpid, id_t, c_uint, getrlimit, rlimit, RLIMIT_NOFILE, getrusage, rusage, RUSAGE_SELF};
use std::alloc::{alloc, Layout, dealloc};
use std::mem::{size_of, align_of};
fn main() {
unsafe {
let pri = getpriority(PRIO_PROCESS as c_uint, getpid() as id_t);
println!("getpriority = {}", pri);
let layout = Layout::from_size_align(size_of::<rlimit>(), align_of::<rlimit>()).unwrap();
let limit_ptr = alloc(layout) as *mut rlimit;
getrlimit(RLIMIT_NOFILE, limit_ptr);
println!("{}, {}", (*limit_ptr).rlim_cur, (*limit_ptr).rlim_max);
dealloc(limit_ptr as *mut u8, layout);
let layout = Layout::from_size_align(size_of::<rusage>(), align_of::<rusage>()).unwrap();
let rusage_ptr = alloc(layout) as *mut rusage;
getrusage(RUSAGE_SELF, rusage_ptr);
println!("{}, {}", (*rusage_ptr).ru_utime.tv_sec, (*rusage_ptr).ru_stime.tv_sec);
dealloc(rusage_ptr as *mut u8, layout);
}
} |
macro_rules! wolfssl_digest_benches {
( $name:ident, $block_len:expr, $digest_len:expr, $t:ty, $init:expr, $update:expr, $final:expr) => {
mod $name {
use ffi;
use std::mem;
digest_benches!($block_len as usize, input, {
unsafe {
let mut sha: $t = mem::uninitialized();
let mut hash: [ffi::byte; $digest_len as usize];
hash = mem::uninitialized();
let _ = $init(&mut sha);
let _ = $update(&mut sha,
input.as_ptr() as *const ffi::byte,
input.len() as ffi::word32);
let _ = $final(&mut sha, hash.as_mut_ptr() as *mut ffi::byte);
}
});
}
}
}
#[cfg(target_os = "linux")]
mod bench_sha {
wolfssl_digest_benches!(
sha1,
ffi::WC_SHA_BLOCK_SIZE,
ffi::WC_SHA_DIGEST_SIZE,
ffi::wc_Sha,
ffi::wc_InitSha,
ffi::wc_ShaUpdate,
ffi::wc_ShaFinal
);
wolfssl_digest_benches!(
sha256,
ffi::WC_SHA256_BLOCK_SIZE,
ffi::WC_SHA256_DIGEST_SIZE,
ffi::wc_Sha256,
ffi::wc_InitSha256,
ffi::wc_Sha256Update,
ffi::wc_Sha256Final
);
/*wolfssl_digest_benches!(
sha384,
ffi::WC_SHA384_BLOCK_SIZE,
ffi::WC_SHA384_DIGEST_SIZE,
ffi::wc_Sha384,
ffi::wc_InitSha384,
ffi::wc_Sha384Update,
ffi::wc_Sha384Final
);
wolfssl_digest_benches!(
sha512,
ffi::WC_SHA512_BLOCK_SIZE,
ffi::WC_SHA512_DIGEST_SIZE,
ffi::wc_Sha512,
ffi::wc_InitSha512,
ffi::wc_Sha512Update,
ffi::wc_Sha512Final
);*/ // disabled for wolfSSL 3.14
}
#[cfg(target_os = "macos")]
mod bench_sha {
wolfssl_digest_benches!(
sha1,
ffi::SHA_BLOCK_SIZE,
ffi::SHA_DIGEST_SIZE,
ffi::Sha,
ffi::wc_InitSha,
ffi::wc_ShaUpdate,
ffi::wc_ShaFinal
);
wolfssl_digest_benches!(
sha256,
ffi::SHA256_BLOCK_SIZE,
ffi::SHA256_DIGEST_SIZE,
ffi::Sha256,
ffi::wc_InitSha256,
ffi::wc_Sha256Update,
ffi::wc_Sha256Final
);
/*wolfssl_digest_benches!(
sha384,
ffi::SHA384_BLOCK_SIZE,
ffi::SHA384_DIGEST_SIZE,
ffi::Sha384,
ffi::wc_InitSha384,
ffi::wc_Sha384Update,
ffi::wc_Sha384Final
);
wolfssl_digest_benches!(
sha512,
ffi::SHA512_BLOCK_SIZE,
ffi::SHA512_DIGEST_SIZE,
ffi::Sha512,
ffi::wc_InitSha512,
ffi::wc_Sha512Update,
ffi::wc_Sha512Final
);*/ // disabled for wolfSSL 3.14
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn AssignProcessToJobObject<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hjob: Param0, hprocess: Param1) -> super::super::Foundation::BOOL {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn AssignProcessToJobObject(hjob: super::super::Foundation::HANDLE, hprocess: super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL;
}
::core::mem::transmute(AssignProcessToJobObject(hjob.into_param().abi(), hprocess.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
#[inline]
pub unsafe fn CreateJobObjectA<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(lpjobattributes: *const super::super::Security::SECURITY_ATTRIBUTES, lpname: Param1) -> super::super::Foundation::HANDLE {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CreateJobObjectA(lpjobattributes: *const super::super::Security::SECURITY_ATTRIBUTES, lpname: super::super::Foundation::PSTR) -> super::super::Foundation::HANDLE;
}
::core::mem::transmute(CreateJobObjectA(::core::mem::transmute(lpjobattributes), lpname.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
#[inline]
pub unsafe fn CreateJobObjectW<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(lpjobattributes: *const super::super::Security::SECURITY_ATTRIBUTES, lpname: Param1) -> super::super::Foundation::HANDLE {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CreateJobObjectW(lpjobattributes: *const super::super::Security::SECURITY_ATTRIBUTES, lpname: super::super::Foundation::PWSTR) -> super::super::Foundation::HANDLE;
}
::core::mem::transmute(CreateJobObjectW(::core::mem::transmute(lpjobattributes), lpname.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn CreateJobSet(numjob: u32, userjobset: *const JOB_SET_ARRAY, flags: u32) -> super::super::Foundation::BOOL {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CreateJobSet(numjob: u32, userjobset: *const JOB_SET_ARRAY, flags: u32) -> super::super::Foundation::BOOL;
}
::core::mem::transmute(CreateJobSet(::core::mem::transmute(numjob), ::core::mem::transmute(userjobset), ::core::mem::transmute(flags)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn FreeMemoryJobObject(buffer: *const ::core::ffi::c_void) {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn FreeMemoryJobObject(buffer: *const ::core::ffi::c_void);
}
::core::mem::transmute(FreeMemoryJobObject(::core::mem::transmute(buffer)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn IsProcessInJob<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(processhandle: Param0, jobhandle: Param1, result: *mut super::super::Foundation::BOOL) -> super::super::Foundation::BOOL {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn IsProcessInJob(processhandle: super::super::Foundation::HANDLE, jobhandle: super::super::Foundation::HANDLE, result: *mut super::super::Foundation::BOOL) -> super::super::Foundation::BOOL;
}
::core::mem::transmute(IsProcessInJob(processhandle.into_param().abi(), jobhandle.into_param().abi(), ::core::mem::transmute(result)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JOBOBJECTINFOCLASS(pub i32);
pub const JobObjectBasicAccountingInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(1i32);
pub const JobObjectBasicLimitInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(2i32);
pub const JobObjectBasicProcessIdList: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(3i32);
pub const JobObjectBasicUIRestrictions: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(4i32);
pub const JobObjectSecurityLimitInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(5i32);
pub const JobObjectEndOfJobTimeInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(6i32);
pub const JobObjectAssociateCompletionPortInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(7i32);
pub const JobObjectBasicAndIoAccountingInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(8i32);
pub const JobObjectExtendedLimitInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(9i32);
pub const JobObjectJobSetInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(10i32);
pub const JobObjectGroupInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(11i32);
pub const JobObjectNotificationLimitInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(12i32);
pub const JobObjectLimitViolationInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(13i32);
pub const JobObjectGroupInformationEx: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(14i32);
pub const JobObjectCpuRateControlInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(15i32);
pub const JobObjectCompletionFilter: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(16i32);
pub const JobObjectCompletionCounter: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(17i32);
pub const JobObjectReserved1Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(18i32);
pub const JobObjectReserved2Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(19i32);
pub const JobObjectReserved3Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(20i32);
pub const JobObjectReserved4Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(21i32);
pub const JobObjectReserved5Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(22i32);
pub const JobObjectReserved6Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(23i32);
pub const JobObjectReserved7Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(24i32);
pub const JobObjectReserved8Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(25i32);
pub const JobObjectReserved9Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(26i32);
pub const JobObjectReserved10Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(27i32);
pub const JobObjectReserved11Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(28i32);
pub const JobObjectReserved12Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(29i32);
pub const JobObjectReserved13Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(30i32);
pub const JobObjectReserved14Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(31i32);
pub const JobObjectNetRateControlInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(32i32);
pub const JobObjectNotificationLimitInformation2: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(33i32);
pub const JobObjectLimitViolationInformation2: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(34i32);
pub const JobObjectCreateSilo: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(35i32);
pub const JobObjectSiloBasicInformation: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(36i32);
pub const JobObjectReserved15Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(37i32);
pub const JobObjectReserved16Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(38i32);
pub const JobObjectReserved17Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(39i32);
pub const JobObjectReserved18Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(40i32);
pub const JobObjectReserved19Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(41i32);
pub const JobObjectReserved20Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(42i32);
pub const JobObjectReserved21Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(43i32);
pub const JobObjectReserved22Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(44i32);
pub const JobObjectReserved23Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(45i32);
pub const JobObjectReserved24Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(46i32);
pub const JobObjectReserved25Information: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(47i32);
pub const MaxJobObjectInfoClass: JOBOBJECTINFOCLASS = JOBOBJECTINFOCLASS(48i32);
impl ::core::convert::From<i32> for JOBOBJECTINFOCLASS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JOBOBJECTINFOCLASS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct JOBOBJECT_ASSOCIATE_COMPLETION_PORT {
pub CompletionKey: *mut ::core::ffi::c_void,
pub CompletionPort: super::super::Foundation::HANDLE,
}
#[cfg(feature = "Win32_Foundation")]
impl JOBOBJECT_ASSOCIATE_COMPLETION_PORT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for JOBOBJECT_ASSOCIATE_COMPLETION_PORT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for JOBOBJECT_ASSOCIATE_COMPLETION_PORT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_ASSOCIATE_COMPLETION_PORT").field("CompletionKey", &self.CompletionKey).field("CompletionPort", &self.CompletionPort).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for JOBOBJECT_ASSOCIATE_COMPLETION_PORT {
fn eq(&self, other: &Self) -> bool {
self.CompletionKey == other.CompletionKey && self.CompletionPort == other.CompletionPort
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for JOBOBJECT_ASSOCIATE_COMPLETION_PORT {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for JOBOBJECT_ASSOCIATE_COMPLETION_PORT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_BASIC_ACCOUNTING_INFORMATION {
pub TotalUserTime: i64,
pub TotalKernelTime: i64,
pub ThisPeriodTotalUserTime: i64,
pub ThisPeriodTotalKernelTime: i64,
pub TotalPageFaultCount: u32,
pub TotalProcesses: u32,
pub ActiveProcesses: u32,
pub TotalTerminatedProcesses: u32,
}
impl JOBOBJECT_BASIC_ACCOUNTING_INFORMATION {}
impl ::core::default::Default for JOBOBJECT_BASIC_ACCOUNTING_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_BASIC_ACCOUNTING_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_BASIC_ACCOUNTING_INFORMATION")
.field("TotalUserTime", &self.TotalUserTime)
.field("TotalKernelTime", &self.TotalKernelTime)
.field("ThisPeriodTotalUserTime", &self.ThisPeriodTotalUserTime)
.field("ThisPeriodTotalKernelTime", &self.ThisPeriodTotalKernelTime)
.field("TotalPageFaultCount", &self.TotalPageFaultCount)
.field("TotalProcesses", &self.TotalProcesses)
.field("ActiveProcesses", &self.ActiveProcesses)
.field("TotalTerminatedProcesses", &self.TotalTerminatedProcesses)
.finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_BASIC_ACCOUNTING_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.TotalUserTime == other.TotalUserTime && self.TotalKernelTime == other.TotalKernelTime && self.ThisPeriodTotalUserTime == other.ThisPeriodTotalUserTime && self.ThisPeriodTotalKernelTime == other.ThisPeriodTotalKernelTime && self.TotalPageFaultCount == other.TotalPageFaultCount && self.TotalProcesses == other.TotalProcesses && self.ActiveProcesses == other.ActiveProcesses && self.TotalTerminatedProcesses == other.TotalTerminatedProcesses
}
}
impl ::core::cmp::Eq for JOBOBJECT_BASIC_ACCOUNTING_INFORMATION {}
unsafe impl ::windows::core::Abi for JOBOBJECT_BASIC_ACCOUNTING_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_System_Threading")]
pub struct JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION {
pub BasicInfo: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION,
pub IoInfo: super::Threading::IO_COUNTERS,
}
#[cfg(feature = "Win32_System_Threading")]
impl JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION {}
#[cfg(feature = "Win32_System_Threading")]
impl ::core::default::Default for JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_System_Threading")]
impl ::core::fmt::Debug for JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION").field("BasicInfo", &self.BasicInfo).field("IoInfo", &self.IoInfo).finish()
}
}
#[cfg(feature = "Win32_System_Threading")]
impl ::core::cmp::PartialEq for JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.BasicInfo == other.BasicInfo && self.IoInfo == other.IoInfo
}
}
#[cfg(feature = "Win32_System_Threading")]
impl ::core::cmp::Eq for JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION {}
#[cfg(feature = "Win32_System_Threading")]
unsafe impl ::windows::core::Abi for JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_BASIC_LIMIT_INFORMATION {
pub PerProcessUserTimeLimit: i64,
pub PerJobUserTimeLimit: i64,
pub LimitFlags: JOB_OBJECT_LIMIT,
pub MinimumWorkingSetSize: usize,
pub MaximumWorkingSetSize: usize,
pub ActiveProcessLimit: u32,
pub Affinity: usize,
pub PriorityClass: u32,
pub SchedulingClass: u32,
}
impl JOBOBJECT_BASIC_LIMIT_INFORMATION {}
impl ::core::default::Default for JOBOBJECT_BASIC_LIMIT_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_BASIC_LIMIT_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_BASIC_LIMIT_INFORMATION")
.field("PerProcessUserTimeLimit", &self.PerProcessUserTimeLimit)
.field("PerJobUserTimeLimit", &self.PerJobUserTimeLimit)
.field("LimitFlags", &self.LimitFlags)
.field("MinimumWorkingSetSize", &self.MinimumWorkingSetSize)
.field("MaximumWorkingSetSize", &self.MaximumWorkingSetSize)
.field("ActiveProcessLimit", &self.ActiveProcessLimit)
.field("Affinity", &self.Affinity)
.field("PriorityClass", &self.PriorityClass)
.field("SchedulingClass", &self.SchedulingClass)
.finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_BASIC_LIMIT_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.PerProcessUserTimeLimit == other.PerProcessUserTimeLimit && self.PerJobUserTimeLimit == other.PerJobUserTimeLimit && self.LimitFlags == other.LimitFlags && self.MinimumWorkingSetSize == other.MinimumWorkingSetSize && self.MaximumWorkingSetSize == other.MaximumWorkingSetSize && self.ActiveProcessLimit == other.ActiveProcessLimit && self.Affinity == other.Affinity && self.PriorityClass == other.PriorityClass && self.SchedulingClass == other.SchedulingClass
}
}
impl ::core::cmp::Eq for JOBOBJECT_BASIC_LIMIT_INFORMATION {}
unsafe impl ::windows::core::Abi for JOBOBJECT_BASIC_LIMIT_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_BASIC_PROCESS_ID_LIST {
pub NumberOfAssignedProcesses: u32,
pub NumberOfProcessIdsInList: u32,
pub ProcessIdList: [usize; 1],
}
impl JOBOBJECT_BASIC_PROCESS_ID_LIST {}
impl ::core::default::Default for JOBOBJECT_BASIC_PROCESS_ID_LIST {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_BASIC_PROCESS_ID_LIST {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_BASIC_PROCESS_ID_LIST").field("NumberOfAssignedProcesses", &self.NumberOfAssignedProcesses).field("NumberOfProcessIdsInList", &self.NumberOfProcessIdsInList).field("ProcessIdList", &self.ProcessIdList).finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_BASIC_PROCESS_ID_LIST {
fn eq(&self, other: &Self) -> bool {
self.NumberOfAssignedProcesses == other.NumberOfAssignedProcesses && self.NumberOfProcessIdsInList == other.NumberOfProcessIdsInList && self.ProcessIdList == other.ProcessIdList
}
}
impl ::core::cmp::Eq for JOBOBJECT_BASIC_PROCESS_ID_LIST {}
unsafe impl ::windows::core::Abi for JOBOBJECT_BASIC_PROCESS_ID_LIST {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_BASIC_UI_RESTRICTIONS {
pub UIRestrictionsClass: JOB_OBJECT_UILIMIT,
}
impl JOBOBJECT_BASIC_UI_RESTRICTIONS {}
impl ::core::default::Default for JOBOBJECT_BASIC_UI_RESTRICTIONS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_BASIC_UI_RESTRICTIONS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_BASIC_UI_RESTRICTIONS").field("UIRestrictionsClass", &self.UIRestrictionsClass).finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_BASIC_UI_RESTRICTIONS {
fn eq(&self, other: &Self) -> bool {
self.UIRestrictionsClass == other.UIRestrictionsClass
}
}
impl ::core::cmp::Eq for JOBOBJECT_BASIC_UI_RESTRICTIONS {}
unsafe impl ::windows::core::Abi for JOBOBJECT_BASIC_UI_RESTRICTIONS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_CPU_RATE_CONTROL_INFORMATION {
pub ControlFlags: JOB_OBJECT_CPU_RATE_CONTROL,
pub Anonymous: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0,
}
impl JOBOBJECT_CPU_RATE_CONTROL_INFORMATION {}
impl ::core::default::Default for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION {}
unsafe impl ::windows::core::Abi for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0 {
pub CpuRate: u32,
pub Weight: u32,
pub Anonymous: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0_0,
}
impl JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0 {}
impl ::core::default::Default for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0 {}
unsafe impl ::windows::core::Abi for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0_0 {
pub MinRate: u16,
pub MaxRate: u16,
}
impl JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0_0 {}
impl ::core::default::Default for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("MinRate", &self.MinRate).field("MaxRate", &self.MaxRate).finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0_0 {
fn eq(&self, other: &Self) -> bool {
self.MinRate == other.MinRate && self.MaxRate == other.MaxRate
}
}
impl ::core::cmp::Eq for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0_0 {}
unsafe impl ::windows::core::Abi for JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_END_OF_JOB_TIME_INFORMATION {
pub EndOfJobTimeAction: JOB_OBJECT_TERMINATE_AT_END_ACTION,
}
impl JOBOBJECT_END_OF_JOB_TIME_INFORMATION {}
impl ::core::default::Default for JOBOBJECT_END_OF_JOB_TIME_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_END_OF_JOB_TIME_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_END_OF_JOB_TIME_INFORMATION").field("EndOfJobTimeAction", &self.EndOfJobTimeAction).finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_END_OF_JOB_TIME_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.EndOfJobTimeAction == other.EndOfJobTimeAction
}
}
impl ::core::cmp::Eq for JOBOBJECT_END_OF_JOB_TIME_INFORMATION {}
unsafe impl ::windows::core::Abi for JOBOBJECT_END_OF_JOB_TIME_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_System_Threading")]
pub struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
pub BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION,
pub IoInfo: super::Threading::IO_COUNTERS,
pub ProcessMemoryLimit: usize,
pub JobMemoryLimit: usize,
pub PeakProcessMemoryUsed: usize,
pub PeakJobMemoryUsed: usize,
}
#[cfg(feature = "Win32_System_Threading")]
impl JOBOBJECT_EXTENDED_LIMIT_INFORMATION {}
#[cfg(feature = "Win32_System_Threading")]
impl ::core::default::Default for JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_System_Threading")]
impl ::core::fmt::Debug for JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_EXTENDED_LIMIT_INFORMATION")
.field("BasicLimitInformation", &self.BasicLimitInformation)
.field("IoInfo", &self.IoInfo)
.field("ProcessMemoryLimit", &self.ProcessMemoryLimit)
.field("JobMemoryLimit", &self.JobMemoryLimit)
.field("PeakProcessMemoryUsed", &self.PeakProcessMemoryUsed)
.field("PeakJobMemoryUsed", &self.PeakJobMemoryUsed)
.finish()
}
}
#[cfg(feature = "Win32_System_Threading")]
impl ::core::cmp::PartialEq for JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.BasicLimitInformation == other.BasicLimitInformation && self.IoInfo == other.IoInfo && self.ProcessMemoryLimit == other.ProcessMemoryLimit && self.JobMemoryLimit == other.JobMemoryLimit && self.PeakProcessMemoryUsed == other.PeakProcessMemoryUsed && self.PeakJobMemoryUsed == other.PeakJobMemoryUsed
}
}
#[cfg(feature = "Win32_System_Threading")]
impl ::core::cmp::Eq for JOBOBJECT_EXTENDED_LIMIT_INFORMATION {}
#[cfg(feature = "Win32_System_Threading")]
unsafe impl ::windows::core::Abi for JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS(pub i32);
pub const JOBOBJECT_IO_ATTRIBUTION_CONTROL_ENABLE: JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS = JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS(1i32);
pub const JOBOBJECT_IO_ATTRIBUTION_CONTROL_DISABLE: JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS = JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS(2i32);
pub const JOBOBJECT_IO_ATTRIBUTION_CONTROL_VALID_FLAGS: JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS = JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS(3i32);
impl ::core::convert::From<i32> for JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_IO_ATTRIBUTION_INFORMATION {
pub ControlFlags: u32,
pub ReadStats: JOBOBJECT_IO_ATTRIBUTION_STATS,
pub WriteStats: JOBOBJECT_IO_ATTRIBUTION_STATS,
}
impl JOBOBJECT_IO_ATTRIBUTION_INFORMATION {}
impl ::core::default::Default for JOBOBJECT_IO_ATTRIBUTION_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_IO_ATTRIBUTION_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_IO_ATTRIBUTION_INFORMATION").field("ControlFlags", &self.ControlFlags).field("ReadStats", &self.ReadStats).field("WriteStats", &self.WriteStats).finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_IO_ATTRIBUTION_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.ControlFlags == other.ControlFlags && self.ReadStats == other.ReadStats && self.WriteStats == other.WriteStats
}
}
impl ::core::cmp::Eq for JOBOBJECT_IO_ATTRIBUTION_INFORMATION {}
unsafe impl ::windows::core::Abi for JOBOBJECT_IO_ATTRIBUTION_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_IO_ATTRIBUTION_STATS {
pub IoCount: usize,
pub TotalNonOverlappedQueueTime: u64,
pub TotalNonOverlappedServiceTime: u64,
pub TotalSize: u64,
}
impl JOBOBJECT_IO_ATTRIBUTION_STATS {}
impl ::core::default::Default for JOBOBJECT_IO_ATTRIBUTION_STATS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_IO_ATTRIBUTION_STATS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_IO_ATTRIBUTION_STATS").field("IoCount", &self.IoCount).field("TotalNonOverlappedQueueTime", &self.TotalNonOverlappedQueueTime).field("TotalNonOverlappedServiceTime", &self.TotalNonOverlappedServiceTime).field("TotalSize", &self.TotalSize).finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_IO_ATTRIBUTION_STATS {
fn eq(&self, other: &Self) -> bool {
self.IoCount == other.IoCount && self.TotalNonOverlappedQueueTime == other.TotalNonOverlappedQueueTime && self.TotalNonOverlappedServiceTime == other.TotalNonOverlappedServiceTime && self.TotalSize == other.TotalSize
}
}
impl ::core::cmp::Eq for JOBOBJECT_IO_ATTRIBUTION_STATS {}
unsafe impl ::windows::core::Abi for JOBOBJECT_IO_ATTRIBUTION_STATS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct JOBOBJECT_IO_RATE_CONTROL_INFORMATION {
pub MaxIops: i64,
pub MaxBandwidth: i64,
pub ReservationIops: i64,
pub VolumeName: super::super::Foundation::PWSTR,
pub BaseIoSize: u32,
pub ControlFlags: JOB_OBJECT_IO_RATE_CONTROL_FLAGS,
}
#[cfg(feature = "Win32_Foundation")]
impl JOBOBJECT_IO_RATE_CONTROL_INFORMATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for JOBOBJECT_IO_RATE_CONTROL_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for JOBOBJECT_IO_RATE_CONTROL_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_IO_RATE_CONTROL_INFORMATION")
.field("MaxIops", &self.MaxIops)
.field("MaxBandwidth", &self.MaxBandwidth)
.field("ReservationIops", &self.ReservationIops)
.field("VolumeName", &self.VolumeName)
.field("BaseIoSize", &self.BaseIoSize)
.field("ControlFlags", &self.ControlFlags)
.finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for JOBOBJECT_IO_RATE_CONTROL_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.MaxIops == other.MaxIops && self.MaxBandwidth == other.MaxBandwidth && self.ReservationIops == other.ReservationIops && self.VolumeName == other.VolumeName && self.BaseIoSize == other.BaseIoSize && self.ControlFlags == other.ControlFlags
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for JOBOBJECT_IO_RATE_CONTROL_INFORMATION {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for JOBOBJECT_IO_RATE_CONTROL_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE {
pub MaxIops: i64,
pub MaxBandwidth: i64,
pub ReservationIops: i64,
pub VolumeName: super::super::Foundation::PWSTR,
pub BaseIoSize: u32,
pub ControlFlags: JOB_OBJECT_IO_RATE_CONTROL_FLAGS,
pub VolumeNameLength: u16,
}
#[cfg(feature = "Win32_Foundation")]
impl JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE")
.field("MaxIops", &self.MaxIops)
.field("MaxBandwidth", &self.MaxBandwidth)
.field("ReservationIops", &self.ReservationIops)
.field("VolumeName", &self.VolumeName)
.field("BaseIoSize", &self.BaseIoSize)
.field("ControlFlags", &self.ControlFlags)
.field("VolumeNameLength", &self.VolumeNameLength)
.finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE {
fn eq(&self, other: &Self) -> bool {
self.MaxIops == other.MaxIops && self.MaxBandwidth == other.MaxBandwidth && self.ReservationIops == other.ReservationIops && self.VolumeName == other.VolumeName && self.BaseIoSize == other.BaseIoSize && self.ControlFlags == other.ControlFlags && self.VolumeNameLength == other.VolumeNameLength
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V2 {
pub MaxIops: i64,
pub MaxBandwidth: i64,
pub ReservationIops: i64,
pub VolumeName: super::super::Foundation::PWSTR,
pub BaseIoSize: u32,
pub ControlFlags: JOB_OBJECT_IO_RATE_CONTROL_FLAGS,
pub VolumeNameLength: u16,
pub CriticalReservationIops: i64,
pub ReservationBandwidth: i64,
pub CriticalReservationBandwidth: i64,
pub MaxTimePercent: i64,
pub ReservationTimePercent: i64,
pub CriticalReservationTimePercent: i64,
}
#[cfg(feature = "Win32_Foundation")]
impl JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V2 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V2 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V2 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V2")
.field("MaxIops", &self.MaxIops)
.field("MaxBandwidth", &self.MaxBandwidth)
.field("ReservationIops", &self.ReservationIops)
.field("VolumeName", &self.VolumeName)
.field("BaseIoSize", &self.BaseIoSize)
.field("ControlFlags", &self.ControlFlags)
.field("VolumeNameLength", &self.VolumeNameLength)
.field("CriticalReservationIops", &self.CriticalReservationIops)
.field("ReservationBandwidth", &self.ReservationBandwidth)
.field("CriticalReservationBandwidth", &self.CriticalReservationBandwidth)
.field("MaxTimePercent", &self.MaxTimePercent)
.field("ReservationTimePercent", &self.ReservationTimePercent)
.field("CriticalReservationTimePercent", &self.CriticalReservationTimePercent)
.finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V2 {
fn eq(&self, other: &Self) -> bool {
self.MaxIops == other.MaxIops
&& self.MaxBandwidth == other.MaxBandwidth
&& self.ReservationIops == other.ReservationIops
&& self.VolumeName == other.VolumeName
&& self.BaseIoSize == other.BaseIoSize
&& self.ControlFlags == other.ControlFlags
&& self.VolumeNameLength == other.VolumeNameLength
&& self.CriticalReservationIops == other.CriticalReservationIops
&& self.ReservationBandwidth == other.ReservationBandwidth
&& self.CriticalReservationBandwidth == other.CriticalReservationBandwidth
&& self.MaxTimePercent == other.MaxTimePercent
&& self.ReservationTimePercent == other.ReservationTimePercent
&& self.CriticalReservationTimePercent == other.CriticalReservationTimePercent
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V2 {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V2 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V3 {
pub MaxIops: i64,
pub MaxBandwidth: i64,
pub ReservationIops: i64,
pub VolumeName: super::super::Foundation::PWSTR,
pub BaseIoSize: u32,
pub ControlFlags: JOB_OBJECT_IO_RATE_CONTROL_FLAGS,
pub VolumeNameLength: u16,
pub CriticalReservationIops: i64,
pub ReservationBandwidth: i64,
pub CriticalReservationBandwidth: i64,
pub MaxTimePercent: i64,
pub ReservationTimePercent: i64,
pub CriticalReservationTimePercent: i64,
pub SoftMaxIops: i64,
pub SoftMaxBandwidth: i64,
pub SoftMaxTimePercent: i64,
pub LimitExcessNotifyIops: i64,
pub LimitExcessNotifyBandwidth: i64,
pub LimitExcessNotifyTimePercent: i64,
}
#[cfg(feature = "Win32_Foundation")]
impl JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V3 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V3 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V3 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V3")
.field("MaxIops", &self.MaxIops)
.field("MaxBandwidth", &self.MaxBandwidth)
.field("ReservationIops", &self.ReservationIops)
.field("VolumeName", &self.VolumeName)
.field("BaseIoSize", &self.BaseIoSize)
.field("ControlFlags", &self.ControlFlags)
.field("VolumeNameLength", &self.VolumeNameLength)
.field("CriticalReservationIops", &self.CriticalReservationIops)
.field("ReservationBandwidth", &self.ReservationBandwidth)
.field("CriticalReservationBandwidth", &self.CriticalReservationBandwidth)
.field("MaxTimePercent", &self.MaxTimePercent)
.field("ReservationTimePercent", &self.ReservationTimePercent)
.field("CriticalReservationTimePercent", &self.CriticalReservationTimePercent)
.field("SoftMaxIops", &self.SoftMaxIops)
.field("SoftMaxBandwidth", &self.SoftMaxBandwidth)
.field("SoftMaxTimePercent", &self.SoftMaxTimePercent)
.field("LimitExcessNotifyIops", &self.LimitExcessNotifyIops)
.field("LimitExcessNotifyBandwidth", &self.LimitExcessNotifyBandwidth)
.field("LimitExcessNotifyTimePercent", &self.LimitExcessNotifyTimePercent)
.finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V3 {
fn eq(&self, other: &Self) -> bool {
self.MaxIops == other.MaxIops
&& self.MaxBandwidth == other.MaxBandwidth
&& self.ReservationIops == other.ReservationIops
&& self.VolumeName == other.VolumeName
&& self.BaseIoSize == other.BaseIoSize
&& self.ControlFlags == other.ControlFlags
&& self.VolumeNameLength == other.VolumeNameLength
&& self.CriticalReservationIops == other.CriticalReservationIops
&& self.ReservationBandwidth == other.ReservationBandwidth
&& self.CriticalReservationBandwidth == other.CriticalReservationBandwidth
&& self.MaxTimePercent == other.MaxTimePercent
&& self.ReservationTimePercent == other.ReservationTimePercent
&& self.CriticalReservationTimePercent == other.CriticalReservationTimePercent
&& self.SoftMaxIops == other.SoftMaxIops
&& self.SoftMaxBandwidth == other.SoftMaxBandwidth
&& self.SoftMaxTimePercent == other.SoftMaxTimePercent
&& self.LimitExcessNotifyIops == other.LimitExcessNotifyIops
&& self.LimitExcessNotifyBandwidth == other.LimitExcessNotifyBandwidth
&& self.LimitExcessNotifyTimePercent == other.LimitExcessNotifyTimePercent
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V3 {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V3 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_JOBSET_INFORMATION {
pub MemberLevel: u32,
}
impl JOBOBJECT_JOBSET_INFORMATION {}
impl ::core::default::Default for JOBOBJECT_JOBSET_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_JOBSET_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_JOBSET_INFORMATION").field("MemberLevel", &self.MemberLevel).finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_JOBSET_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.MemberLevel == other.MemberLevel
}
}
impl ::core::cmp::Eq for JOBOBJECT_JOBSET_INFORMATION {}
unsafe impl ::windows::core::Abi for JOBOBJECT_JOBSET_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_LIMIT_VIOLATION_INFORMATION {
pub LimitFlags: JOB_OBJECT_LIMIT,
pub ViolationLimitFlags: JOB_OBJECT_LIMIT,
pub IoReadBytes: u64,
pub IoReadBytesLimit: u64,
pub IoWriteBytes: u64,
pub IoWriteBytesLimit: u64,
pub PerJobUserTime: i64,
pub PerJobUserTimeLimit: i64,
pub JobMemory: u64,
pub JobMemoryLimit: u64,
pub RateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
pub RateControlToleranceLimit: JOBOBJECT_RATE_CONTROL_TOLERANCE,
}
impl JOBOBJECT_LIMIT_VIOLATION_INFORMATION {}
impl ::core::default::Default for JOBOBJECT_LIMIT_VIOLATION_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_LIMIT_VIOLATION_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_LIMIT_VIOLATION_INFORMATION")
.field("LimitFlags", &self.LimitFlags)
.field("ViolationLimitFlags", &self.ViolationLimitFlags)
.field("IoReadBytes", &self.IoReadBytes)
.field("IoReadBytesLimit", &self.IoReadBytesLimit)
.field("IoWriteBytes", &self.IoWriteBytes)
.field("IoWriteBytesLimit", &self.IoWriteBytesLimit)
.field("PerJobUserTime", &self.PerJobUserTime)
.field("PerJobUserTimeLimit", &self.PerJobUserTimeLimit)
.field("JobMemory", &self.JobMemory)
.field("JobMemoryLimit", &self.JobMemoryLimit)
.field("RateControlTolerance", &self.RateControlTolerance)
.field("RateControlToleranceLimit", &self.RateControlToleranceLimit)
.finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_LIMIT_VIOLATION_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.LimitFlags == other.LimitFlags
&& self.ViolationLimitFlags == other.ViolationLimitFlags
&& self.IoReadBytes == other.IoReadBytes
&& self.IoReadBytesLimit == other.IoReadBytesLimit
&& self.IoWriteBytes == other.IoWriteBytes
&& self.IoWriteBytesLimit == other.IoWriteBytesLimit
&& self.PerJobUserTime == other.PerJobUserTime
&& self.PerJobUserTimeLimit == other.PerJobUserTimeLimit
&& self.JobMemory == other.JobMemory
&& self.JobMemoryLimit == other.JobMemoryLimit
&& self.RateControlTolerance == other.RateControlTolerance
&& self.RateControlToleranceLimit == other.RateControlToleranceLimit
}
}
impl ::core::cmp::Eq for JOBOBJECT_LIMIT_VIOLATION_INFORMATION {}
unsafe impl ::windows::core::Abi for JOBOBJECT_LIMIT_VIOLATION_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2 {
pub LimitFlags: JOB_OBJECT_LIMIT,
pub ViolationLimitFlags: JOB_OBJECT_LIMIT,
pub IoReadBytes: u64,
pub IoReadBytesLimit: u64,
pub IoWriteBytes: u64,
pub IoWriteBytesLimit: u64,
pub PerJobUserTime: i64,
pub PerJobUserTimeLimit: i64,
pub JobMemory: u64,
pub Anonymous1: JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_0,
pub Anonymous2: JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_1,
pub Anonymous3: JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_2,
pub JobLowMemoryLimit: u64,
pub IoRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
pub IoRateControlToleranceLimit: JOBOBJECT_RATE_CONTROL_TOLERANCE,
pub NetRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
pub NetRateControlToleranceLimit: JOBOBJECT_RATE_CONTROL_TOLERANCE,
}
impl JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2 {}
impl ::core::default::Default for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2 {}
unsafe impl ::windows::core::Abi for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_0 {
pub JobHighMemoryLimit: u64,
pub JobMemoryLimit: u64,
}
impl JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_0 {}
impl ::core::default::Default for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_0 {}
unsafe impl ::windows::core::Abi for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_1 {
pub RateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
pub CpuRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
}
impl JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_1 {}
impl ::core::default::Default for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_1 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_1 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_1 {}
unsafe impl ::windows::core::Abi for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_1 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_2 {
pub RateControlToleranceLimit: JOBOBJECT_RATE_CONTROL_TOLERANCE,
pub CpuRateControlToleranceLimit: JOBOBJECT_RATE_CONTROL_TOLERANCE,
}
impl JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_2 {}
impl ::core::default::Default for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_2 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_2 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_2 {}
unsafe impl ::windows::core::Abi for JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2_2 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_NET_RATE_CONTROL_INFORMATION {
pub MaxBandwidth: u64,
pub ControlFlags: JOB_OBJECT_NET_RATE_CONTROL_FLAGS,
pub DscpTag: u8,
}
impl JOBOBJECT_NET_RATE_CONTROL_INFORMATION {}
impl ::core::default::Default for JOBOBJECT_NET_RATE_CONTROL_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_NET_RATE_CONTROL_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_NET_RATE_CONTROL_INFORMATION").field("MaxBandwidth", &self.MaxBandwidth).field("ControlFlags", &self.ControlFlags).field("DscpTag", &self.DscpTag).finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_NET_RATE_CONTROL_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.MaxBandwidth == other.MaxBandwidth && self.ControlFlags == other.ControlFlags && self.DscpTag == other.DscpTag
}
}
impl ::core::cmp::Eq for JOBOBJECT_NET_RATE_CONTROL_INFORMATION {}
unsafe impl ::windows::core::Abi for JOBOBJECT_NET_RATE_CONTROL_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION {
pub IoReadBytesLimit: u64,
pub IoWriteBytesLimit: u64,
pub PerJobUserTimeLimit: i64,
pub JobMemoryLimit: u64,
pub RateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
pub RateControlToleranceInterval: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL,
pub LimitFlags: JOB_OBJECT_LIMIT,
}
impl JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION {}
impl ::core::default::Default for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION")
.field("IoReadBytesLimit", &self.IoReadBytesLimit)
.field("IoWriteBytesLimit", &self.IoWriteBytesLimit)
.field("PerJobUserTimeLimit", &self.PerJobUserTimeLimit)
.field("JobMemoryLimit", &self.JobMemoryLimit)
.field("RateControlTolerance", &self.RateControlTolerance)
.field("RateControlToleranceInterval", &self.RateControlToleranceInterval)
.field("LimitFlags", &self.LimitFlags)
.finish()
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.IoReadBytesLimit == other.IoReadBytesLimit && self.IoWriteBytesLimit == other.IoWriteBytesLimit && self.PerJobUserTimeLimit == other.PerJobUserTimeLimit && self.JobMemoryLimit == other.JobMemoryLimit && self.RateControlTolerance == other.RateControlTolerance && self.RateControlToleranceInterval == other.RateControlToleranceInterval && self.LimitFlags == other.LimitFlags
}
}
impl ::core::cmp::Eq for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION {}
unsafe impl ::windows::core::Abi for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2 {
pub IoReadBytesLimit: u64,
pub IoWriteBytesLimit: u64,
pub PerJobUserTimeLimit: i64,
pub Anonymous1: JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_0,
pub Anonymous2: JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_1,
pub Anonymous3: JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_2,
pub LimitFlags: JOB_OBJECT_LIMIT,
pub IoRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
pub JobLowMemoryLimit: u64,
pub IoRateControlToleranceInterval: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL,
pub NetRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
pub NetRateControlToleranceInterval: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL,
}
impl JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2 {}
impl ::core::default::Default for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2 {}
unsafe impl ::windows::core::Abi for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_0 {
pub JobHighMemoryLimit: u64,
pub JobMemoryLimit: u64,
}
impl JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_0 {}
impl ::core::default::Default for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_0 {}
unsafe impl ::windows::core::Abi for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_1 {
pub RateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
pub CpuRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
}
impl JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_1 {}
impl ::core::default::Default for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_1 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_1 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_1 {}
unsafe impl ::windows::core::Abi for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_1 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_2 {
pub RateControlToleranceInterval: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL,
pub CpuRateControlToleranceInterval: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL,
}
impl JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_2 {}
impl ::core::default::Default for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_2 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_2 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_2 {}
unsafe impl ::windows::core::Abi for JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2_2 {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JOBOBJECT_RATE_CONTROL_TOLERANCE(pub i32);
pub const ToleranceLow: JOBOBJECT_RATE_CONTROL_TOLERANCE = JOBOBJECT_RATE_CONTROL_TOLERANCE(1i32);
pub const ToleranceMedium: JOBOBJECT_RATE_CONTROL_TOLERANCE = JOBOBJECT_RATE_CONTROL_TOLERANCE(2i32);
pub const ToleranceHigh: JOBOBJECT_RATE_CONTROL_TOLERANCE = JOBOBJECT_RATE_CONTROL_TOLERANCE(3i32);
impl ::core::convert::From<i32> for JOBOBJECT_RATE_CONTROL_TOLERANCE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JOBOBJECT_RATE_CONTROL_TOLERANCE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL(pub i32);
pub const ToleranceIntervalShort: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL = JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL(1i32);
pub const ToleranceIntervalMedium: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL = JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL(2i32);
pub const ToleranceIntervalLong: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL = JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL(3i32);
impl ::core::convert::From<i32> for JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
pub struct JOBOBJECT_SECURITY_LIMIT_INFORMATION {
pub SecurityLimitFlags: JOB_OBJECT_SECURITY,
pub JobToken: super::super::Foundation::HANDLE,
pub SidsToDisable: *mut super::super::Security::TOKEN_GROUPS,
pub PrivilegesToDelete: *mut super::super::Security::TOKEN_PRIVILEGES,
pub RestrictedSids: *mut super::super::Security::TOKEN_GROUPS,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl JOBOBJECT_SECURITY_LIMIT_INFORMATION {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::default::Default for JOBOBJECT_SECURITY_LIMIT_INFORMATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::fmt::Debug for JOBOBJECT_SECURITY_LIMIT_INFORMATION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOBOBJECT_SECURITY_LIMIT_INFORMATION").field("SecurityLimitFlags", &self.SecurityLimitFlags).field("JobToken", &self.JobToken).field("SidsToDisable", &self.SidsToDisable).field("PrivilegesToDelete", &self.PrivilegesToDelete).field("RestrictedSids", &self.RestrictedSids).finish()
}
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::cmp::PartialEq for JOBOBJECT_SECURITY_LIMIT_INFORMATION {
fn eq(&self, other: &Self) -> bool {
self.SecurityLimitFlags == other.SecurityLimitFlags && self.JobToken == other.JobToken && self.SidsToDisable == other.SidsToDisable && self.PrivilegesToDelete == other.PrivilegesToDelete && self.RestrictedSids == other.RestrictedSids
}
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::cmp::Eq for JOBOBJECT_SECURITY_LIMIT_INFORMATION {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
unsafe impl ::windows::core::Abi for JOBOBJECT_SECURITY_LIMIT_INFORMATION {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JOB_OBJECT_CPU_RATE_CONTROL(pub u32);
pub const JOB_OBJECT_CPU_RATE_CONTROL_ENABLE: JOB_OBJECT_CPU_RATE_CONTROL = JOB_OBJECT_CPU_RATE_CONTROL(1u32);
pub const JOB_OBJECT_CPU_RATE_CONTROL_WEIGHT_BASED: JOB_OBJECT_CPU_RATE_CONTROL = JOB_OBJECT_CPU_RATE_CONTROL(2u32);
pub const JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP: JOB_OBJECT_CPU_RATE_CONTROL = JOB_OBJECT_CPU_RATE_CONTROL(4u32);
pub const JOB_OBJECT_CPU_RATE_CONTROL_NOTIFY: JOB_OBJECT_CPU_RATE_CONTROL = JOB_OBJECT_CPU_RATE_CONTROL(8u32);
pub const JOB_OBJECT__CPU_RATE_CONTROL_MIN_MAX_RATE: JOB_OBJECT_CPU_RATE_CONTROL = JOB_OBJECT_CPU_RATE_CONTROL(16u32);
impl ::core::convert::From<u32> for JOB_OBJECT_CPU_RATE_CONTROL {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JOB_OBJECT_CPU_RATE_CONTROL {
type Abi = Self;
}
impl ::core::ops::BitOr for JOB_OBJECT_CPU_RATE_CONTROL {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for JOB_OBJECT_CPU_RATE_CONTROL {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for JOB_OBJECT_CPU_RATE_CONTROL {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for JOB_OBJECT_CPU_RATE_CONTROL {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for JOB_OBJECT_CPU_RATE_CONTROL {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JOB_OBJECT_IO_RATE_CONTROL_FLAGS(pub i32);
pub const JOB_OBJECT_IO_RATE_CONTROL_ENABLE: JOB_OBJECT_IO_RATE_CONTROL_FLAGS = JOB_OBJECT_IO_RATE_CONTROL_FLAGS(1i32);
pub const JOB_OBJECT_IO_RATE_CONTROL_STANDALONE_VOLUME: JOB_OBJECT_IO_RATE_CONTROL_FLAGS = JOB_OBJECT_IO_RATE_CONTROL_FLAGS(2i32);
pub const JOB_OBJECT_IO_RATE_CONTROL_FORCE_UNIT_ACCESS_ALL: JOB_OBJECT_IO_RATE_CONTROL_FLAGS = JOB_OBJECT_IO_RATE_CONTROL_FLAGS(4i32);
pub const JOB_OBJECT_IO_RATE_CONTROL_FORCE_UNIT_ACCESS_ON_SOFT_CAP: JOB_OBJECT_IO_RATE_CONTROL_FLAGS = JOB_OBJECT_IO_RATE_CONTROL_FLAGS(8i32);
pub const JOB_OBJECT_IO_RATE_CONTROL_VALID_FLAGS: JOB_OBJECT_IO_RATE_CONTROL_FLAGS = JOB_OBJECT_IO_RATE_CONTROL_FLAGS(15i32);
impl ::core::convert::From<i32> for JOB_OBJECT_IO_RATE_CONTROL_FLAGS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JOB_OBJECT_IO_RATE_CONTROL_FLAGS {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JOB_OBJECT_LIMIT(pub u32);
pub const JOB_OBJECT_LIMIT_WORKINGSET: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(1u32);
pub const JOB_OBJECT_LIMIT_PROCESS_TIME: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(2u32);
pub const JOB_OBJECT_LIMIT_JOB_TIME: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(4u32);
pub const JOB_OBJECT_LIMIT_ACTIVE_PROCESS: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(8u32);
pub const JOB_OBJECT_LIMIT_AFFINITY: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(16u32);
pub const JOB_OBJECT_LIMIT_PRIORITY_CLASS: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(32u32);
pub const JOB_OBJECT_LIMIT_PRESERVE_JOB_TIME: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(64u32);
pub const JOB_OBJECT_LIMIT_SCHEDULING_CLASS: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(128u32);
pub const JOB_OBJECT_LIMIT_PROCESS_MEMORY: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(256u32);
pub const JOB_OBJECT_LIMIT_JOB_MEMORY: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(512u32);
pub const JOB_OBJECT_LIMIT_JOB_MEMORY_HIGH: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(512u32);
pub const JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(1024u32);
pub const JOB_OBJECT_LIMIT_BREAKAWAY_OK: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(2048u32);
pub const JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(4096u32);
pub const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(8192u32);
pub const JOB_OBJECT_LIMIT_SUBSET_AFFINITY: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(16384u32);
pub const JOB_OBJECT_LIMIT_JOB_MEMORY_LOW: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(32768u32);
pub const JOB_OBJECT_LIMIT_JOB_READ_BYTES: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(65536u32);
pub const JOB_OBJECT_LIMIT_JOB_WRITE_BYTES: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(131072u32);
pub const JOB_OBJECT_LIMIT_RATE_CONTROL: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(262144u32);
pub const JOB_OBJECT_LIMIT_CPU_RATE_CONTROL: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(262144u32);
pub const JOB_OBJECT_LIMIT_IO_RATE_CONTROL: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(524288u32);
pub const JOB_OBJECT_LIMIT_NET_RATE_CONTROL: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(1048576u32);
pub const JOB_OBJECT_LIMIT_VALID_FLAGS: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(524287u32);
pub const JOB_OBJECT_BASIC_LIMIT_VALID_FLAGS: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(255u32);
pub const JOB_OBJECT_EXTENDED_LIMIT_VALID_FLAGS: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(32767u32);
pub const JOB_OBJECT_NOTIFICATION_LIMIT_VALID_FLAGS: JOB_OBJECT_LIMIT = JOB_OBJECT_LIMIT(2064900u32);
impl ::core::convert::From<u32> for JOB_OBJECT_LIMIT {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JOB_OBJECT_LIMIT {
type Abi = Self;
}
impl ::core::ops::BitOr for JOB_OBJECT_LIMIT {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for JOB_OBJECT_LIMIT {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for JOB_OBJECT_LIMIT {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for JOB_OBJECT_LIMIT {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for JOB_OBJECT_LIMIT {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JOB_OBJECT_NET_RATE_CONTROL_FLAGS(pub i32);
pub const JOB_OBJECT_NET_RATE_CONTROL_ENABLE: JOB_OBJECT_NET_RATE_CONTROL_FLAGS = JOB_OBJECT_NET_RATE_CONTROL_FLAGS(1i32);
pub const JOB_OBJECT_NET_RATE_CONTROL_MAX_BANDWIDTH: JOB_OBJECT_NET_RATE_CONTROL_FLAGS = JOB_OBJECT_NET_RATE_CONTROL_FLAGS(2i32);
pub const JOB_OBJECT_NET_RATE_CONTROL_DSCP_TAG: JOB_OBJECT_NET_RATE_CONTROL_FLAGS = JOB_OBJECT_NET_RATE_CONTROL_FLAGS(4i32);
pub const JOB_OBJECT_NET_RATE_CONTROL_VALID_FLAGS: JOB_OBJECT_NET_RATE_CONTROL_FLAGS = JOB_OBJECT_NET_RATE_CONTROL_FLAGS(7i32);
impl ::core::convert::From<i32> for JOB_OBJECT_NET_RATE_CONTROL_FLAGS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JOB_OBJECT_NET_RATE_CONTROL_FLAGS {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JOB_OBJECT_SECURITY(pub u32);
pub const JOB_OBJECT_SECURITY_NO_ADMIN: JOB_OBJECT_SECURITY = JOB_OBJECT_SECURITY(1u32);
pub const JOB_OBJECT_SECURITY_RESTRICTED_TOKEN: JOB_OBJECT_SECURITY = JOB_OBJECT_SECURITY(2u32);
pub const JOB_OBJECT_SECURITY_ONLY_TOKEN: JOB_OBJECT_SECURITY = JOB_OBJECT_SECURITY(4u32);
pub const JOB_OBJECT_SECURITY_FILTER_TOKENS: JOB_OBJECT_SECURITY = JOB_OBJECT_SECURITY(8u32);
pub const JOB_OBJECT_SECURITY_VALID_FLAGS: JOB_OBJECT_SECURITY = JOB_OBJECT_SECURITY(15u32);
impl ::core::convert::From<u32> for JOB_OBJECT_SECURITY {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JOB_OBJECT_SECURITY {
type Abi = Self;
}
impl ::core::ops::BitOr for JOB_OBJECT_SECURITY {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for JOB_OBJECT_SECURITY {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for JOB_OBJECT_SECURITY {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for JOB_OBJECT_SECURITY {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for JOB_OBJECT_SECURITY {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JOB_OBJECT_TERMINATE_AT_END_ACTION(pub u32);
pub const JOB_OBJECT_TERMINATE_AT_END_OF_JOB: JOB_OBJECT_TERMINATE_AT_END_ACTION = JOB_OBJECT_TERMINATE_AT_END_ACTION(0u32);
pub const JOB_OBJECT_POST_AT_END_OF_JOB: JOB_OBJECT_TERMINATE_AT_END_ACTION = JOB_OBJECT_TERMINATE_AT_END_ACTION(1u32);
impl ::core::convert::From<u32> for JOB_OBJECT_TERMINATE_AT_END_ACTION {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JOB_OBJECT_TERMINATE_AT_END_ACTION {
type Abi = Self;
}
impl ::core::ops::BitOr for JOB_OBJECT_TERMINATE_AT_END_ACTION {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for JOB_OBJECT_TERMINATE_AT_END_ACTION {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for JOB_OBJECT_TERMINATE_AT_END_ACTION {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for JOB_OBJECT_TERMINATE_AT_END_ACTION {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for JOB_OBJECT_TERMINATE_AT_END_ACTION {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JOB_OBJECT_UILIMIT(pub u32);
pub const JOB_OBJECT_UILIMIT_NONE: JOB_OBJECT_UILIMIT = JOB_OBJECT_UILIMIT(0u32);
pub const JOB_OBJECT_UILIMIT_HANDLES: JOB_OBJECT_UILIMIT = JOB_OBJECT_UILIMIT(1u32);
pub const JOB_OBJECT_UILIMIT_READCLIPBOARD: JOB_OBJECT_UILIMIT = JOB_OBJECT_UILIMIT(2u32);
pub const JOB_OBJECT_UILIMIT_WRITECLIPBOARD: JOB_OBJECT_UILIMIT = JOB_OBJECT_UILIMIT(4u32);
pub const JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS: JOB_OBJECT_UILIMIT = JOB_OBJECT_UILIMIT(8u32);
pub const JOB_OBJECT_UILIMIT_DISPLAYSETTINGS: JOB_OBJECT_UILIMIT = JOB_OBJECT_UILIMIT(16u32);
pub const JOB_OBJECT_UILIMIT_GLOBALATOMS: JOB_OBJECT_UILIMIT = JOB_OBJECT_UILIMIT(32u32);
pub const JOB_OBJECT_UILIMIT_DESKTOP: JOB_OBJECT_UILIMIT = JOB_OBJECT_UILIMIT(64u32);
pub const JOB_OBJECT_UILIMIT_EXITWINDOWS: JOB_OBJECT_UILIMIT = JOB_OBJECT_UILIMIT(128u32);
impl ::core::convert::From<u32> for JOB_OBJECT_UILIMIT {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JOB_OBJECT_UILIMIT {
type Abi = Self;
}
impl ::core::ops::BitOr for JOB_OBJECT_UILIMIT {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for JOB_OBJECT_UILIMIT {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for JOB_OBJECT_UILIMIT {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for JOB_OBJECT_UILIMIT {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for JOB_OBJECT_UILIMIT {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct JOB_SET_ARRAY {
pub JobHandle: super::super::Foundation::HANDLE,
pub MemberLevel: u32,
pub Flags: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl JOB_SET_ARRAY {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for JOB_SET_ARRAY {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for JOB_SET_ARRAY {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("JOB_SET_ARRAY").field("JobHandle", &self.JobHandle).field("MemberLevel", &self.MemberLevel).field("Flags", &self.Flags).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for JOB_SET_ARRAY {
fn eq(&self, other: &Self) -> bool {
self.JobHandle == other.JobHandle && self.MemberLevel == other.MemberLevel && self.Flags == other.Flags
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for JOB_SET_ARRAY {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for JOB_SET_ARRAY {
type Abi = Self;
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn OpenJobObjectA<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(dwdesiredaccess: u32, binherithandle: Param1, lpname: Param2) -> super::super::Foundation::HANDLE {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn OpenJobObjectA(dwdesiredaccess: u32, binherithandle: super::super::Foundation::BOOL, lpname: super::super::Foundation::PSTR) -> super::super::Foundation::HANDLE;
}
::core::mem::transmute(OpenJobObjectA(::core::mem::transmute(dwdesiredaccess), binherithandle.into_param().abi(), lpname.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn OpenJobObjectW<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dwdesiredaccess: u32, binherithandle: Param1, lpname: Param2) -> super::super::Foundation::HANDLE {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn OpenJobObjectW(dwdesiredaccess: u32, binherithandle: super::super::Foundation::BOOL, lpname: super::super::Foundation::PWSTR) -> super::super::Foundation::HANDLE;
}
::core::mem::transmute(OpenJobObjectW(::core::mem::transmute(dwdesiredaccess), binherithandle.into_param().abi(), lpname.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn QueryInformationJobObject<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hjob: Param0, jobobjectinformationclass: JOBOBJECTINFOCLASS, lpjobobjectinformation: *mut ::core::ffi::c_void, cbjobobjectinformationlength: u32, lpreturnlength: *mut u32) -> super::super::Foundation::BOOL {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn QueryInformationJobObject(hjob: super::super::Foundation::HANDLE, jobobjectinformationclass: JOBOBJECTINFOCLASS, lpjobobjectinformation: *mut ::core::ffi::c_void, cbjobobjectinformationlength: u32, lpreturnlength: *mut u32) -> super::super::Foundation::BOOL;
}
::core::mem::transmute(QueryInformationJobObject(hjob.into_param().abi(), ::core::mem::transmute(jobobjectinformationclass), ::core::mem::transmute(lpjobobjectinformation), ::core::mem::transmute(cbjobobjectinformationlength), ::core::mem::transmute(lpreturnlength)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn QueryIoRateControlInformationJobObject<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(hjob: Param0, volumename: Param1, infoblocks: *mut *mut JOBOBJECT_IO_RATE_CONTROL_INFORMATION, infoblockcount: *mut u32) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn QueryIoRateControlInformationJobObject(hjob: super::super::Foundation::HANDLE, volumename: super::super::Foundation::PWSTR, infoblocks: *mut *mut JOBOBJECT_IO_RATE_CONTROL_INFORMATION, infoblockcount: *mut u32) -> u32;
}
::core::mem::transmute(QueryIoRateControlInformationJobObject(hjob.into_param().abi(), volumename.into_param().abi(), ::core::mem::transmute(infoblocks), ::core::mem::transmute(infoblockcount)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn SetInformationJobObject<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hjob: Param0, jobobjectinformationclass: JOBOBJECTINFOCLASS, lpjobobjectinformation: *const ::core::ffi::c_void, cbjobobjectinformationlength: u32) -> super::super::Foundation::BOOL {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn SetInformationJobObject(hjob: super::super::Foundation::HANDLE, jobobjectinformationclass: JOBOBJECTINFOCLASS, lpjobobjectinformation: *const ::core::ffi::c_void, cbjobobjectinformationlength: u32) -> super::super::Foundation::BOOL;
}
::core::mem::transmute(SetInformationJobObject(hjob.into_param().abi(), ::core::mem::transmute(jobobjectinformationclass), ::core::mem::transmute(lpjobobjectinformation), ::core::mem::transmute(cbjobobjectinformationlength)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn SetIoRateControlInformationJobObject<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hjob: Param0, ioratecontrolinfo: *const JOBOBJECT_IO_RATE_CONTROL_INFORMATION) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn SetIoRateControlInformationJobObject(hjob: super::super::Foundation::HANDLE, ioratecontrolinfo: *const JOBOBJECT_IO_RATE_CONTROL_INFORMATION) -> u32;
}
::core::mem::transmute(SetIoRateControlInformationJobObject(hjob.into_param().abi(), ::core::mem::transmute(ioratecontrolinfo)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn TerminateJobObject<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hjob: Param0, uexitcode: u32) -> super::super::Foundation::BOOL {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn TerminateJobObject(hjob: super::super::Foundation::HANDLE, uexitcode: u32) -> super::super::Foundation::BOOL;
}
::core::mem::transmute(TerminateJobObject(hjob.into_param().abi(), ::core::mem::transmute(uexitcode)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn UserHandleGrantAccess<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(huserhandle: Param0, hjob: Param1, bgrant: Param2) -> super::super::Foundation::BOOL {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn UserHandleGrantAccess(huserhandle: super::super::Foundation::HANDLE, hjob: super::super::Foundation::HANDLE, bgrant: super::super::Foundation::BOOL) -> super::super::Foundation::BOOL;
}
::core::mem::transmute(UserHandleGrantAccess(huserhandle.into_param().abi(), hjob.into_param().abi(), bgrant.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
|
mod reader;
pub use self::reader::EventReader;
|
/*
* hurl (https://hurl.dev)
* Copyright (C) 2020 Orange
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
use crate::core::common::{FormatError, Pos, SourceInfo};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Error {
pub pos: Pos,
pub recoverable: bool,
pub inner: ParseError,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParseError {
Expecting { value: String },
Method {},
Version {},
Status {},
Filename {},
FileContentType {},
Space {},
SectionName { name: String },
JsonpathExpr {},
XPathExpr {},
TemplateVariable {},
Json {},
Xml {},
Predicate,
PredicateValue,
RegexExpr,
Unexpected { character: String },
Eof {},
Url {},
DuplicateSection,
RequestSection,
ResponseSection,
HexDigit,
Unicode,
EscapeChar,
InvalidCookieAttribute,
}
impl FormatError for Error {
fn source_info(&self) -> SourceInfo {
SourceInfo {
start: self.pos.clone(),
end: self.pos.clone(),
}
}
fn description(&self) -> String {
match self.clone().inner {
ParseError::Method { .. } => "Parsing Method".to_string(),
ParseError::Version { .. } => "Parsing Version".to_string(),
ParseError::Status { .. } => "Parsing Status".to_string(),
ParseError::Filename { .. } => "Parsing Filename".to_string(),
ParseError::Expecting { .. } => "Parsing literal".to_string(),
ParseError::Space { .. } => "Parsing space".to_string(),
ParseError::SectionName { .. } => "Parsing section name".to_string(),
ParseError::JsonpathExpr { .. } => "Parsing jsonpath expression".to_string(),
ParseError::XPathExpr { .. } => "Parsing xpath expression".to_string(),
ParseError::TemplateVariable { .. } => "Parsing template variable".to_string(),
ParseError::Json { .. } => "Parsing json".to_string(),
ParseError::Predicate { .. } => "Parsing predicate".to_string(),
ParseError::PredicateValue { .. } => "Parsing predicate value".to_string(),
ParseError::RegexExpr { .. } => "Parsing regex".to_string(),
ParseError::DuplicateSection { .. } => "Parsing section".to_string(),
ParseError::RequestSection { .. } => "Parsing section".to_string(),
ParseError::ResponseSection { .. } => "Parsing section".to_string(),
ParseError::EscapeChar { .. } => "Parsing escape character".to_string(),
ParseError::InvalidCookieAttribute { .. } => "Parsing cookie attribute".to_string(),
_ => format!("{:?}", self),
}
}
fn fixme(&self) -> String {
match self.inner.clone() {
ParseError::Method { .. } => "Available HTTP Method GET, POST, ...".to_string(),
ParseError::Version { .. } => "The http version must be 1.0, 1.1, 2 or *".to_string(),
ParseError::Status { .. } => "The http status is not valid".to_string(),
ParseError::Filename { .. } => "expecting a filename".to_string(),
ParseError::Expecting { value } => format!("expecting '{}'", value),
ParseError::Space { .. } => "expecting a space".to_string(),
ParseError::SectionName { name } => format!("the section {} is not valid", name),
ParseError::JsonpathExpr { .. } => "expecting a jsonpath expression".to_string(),
ParseError::XPathExpr { .. } => "expecting a xpath expression".to_string(),
ParseError::TemplateVariable { .. } => "expecting a variable".to_string(),
ParseError::Json { .. } => "json error".to_string(),
ParseError::Predicate { .. } => "expecting a predicate".to_string(),
ParseError::PredicateValue { .. } => "invalid predicate value".to_string(),
ParseError::RegexExpr { .. } => "Invalid Regex expression".to_string(),
ParseError::DuplicateSection { .. } => "The section is already defined".to_string(),
ParseError::RequestSection { .. } => "This is not a valid section for a request".to_string(),
ParseError::ResponseSection { .. } => "This is not a valid section for a response".to_string(),
ParseError::EscapeChar { .. } => "The escaping sequence is not valid".to_string(),
ParseError::InvalidCookieAttribute { .. } => "The cookie attribute is not valid".to_string(),
_ => format!("{:?}", self),
}
}
}
|
use crate::helpers;
use std::collections::HashMap;
pub fn solve(input: String) {
let mut lines: Vec<i64> = helpers::file::to_list(&input)
.iter()
.map(|x| x.parse().unwrap())
.collect();
part1(lines);
part2();
}
fn count_combinations(input: Vec<i64>) -> HashMap<i64, i64> {
let mut res: HashMap<i64, i64> = HashMap::new();
for i in input.clone() {
for j in input.clone() {
let index = i + j;
res.insert(index, 1);
}
}
return res;
}
fn part1(input: Vec<i64>) {
let mut queue: Vec<i64> = Vec::with_capacity(25);
let max_len = input.len();
for i in 0..26 {
queue.push(*input.get(i).unwrap());
}
for i in 26..max_len {
let value = input.get(i).unwrap();
queue.push(*value);
let combinations = count_combinations(queue.clone());
if !combinations.contains_key(value) {
println!("{} {}", i, value);
break;
}
queue.drain(0..1);
}
}
fn part2() {
println!("Not implemented");
}
|
// wre_frame.rs
//
// Copyright (c) 2019, Univerisity of Minnesota
//
// Author: Bridger Herman (herma582@umn.edu)
//! Useful and necessary macros for the Wasm Rendering Engine
#[macro_export]
macro_rules! wre_time {
() => {
*crate::state::WRE_TIME.try_lock().unwrap()
};
}
#[macro_export]
macro_rules! wre_window {
() => {
*crate::state::WRE_WINDOW.try_lock().unwrap()
};
}
#[macro_export]
macro_rules! wre_camera {
() => {
*crate::state::WRE_CAMERA.try_lock().unwrap()
};
}
#[macro_export]
macro_rules! wre_entities {
() => {
*crate::state::WRE_ENTITIES.try_lock().unwrap()
};
($eid:expr) => {
crate::state::WRE_ENTITIES.try_lock().unwrap().get($eid)
};
}
#[macro_export]
macro_rules! wre_entities_mut {
() => {
&mut *crate::state::WRE_ENTITIES.try_lock().unwrap()
};
($eid:expr) => {
&mut *crate::state::WRE_ENTITIES.try_lock().unwrap().get_mut($eid)
};
}
#[macro_export]
macro_rules! wre_scripts {
() => {
*crate::state::WRE_SCRIPTS.try_lock().unwrap()
};
}
#[macro_export]
macro_rules! wre_render_system {
() => {
*crate::state::WRE_RENDER_SYSTEM.try_lock().unwrap()
};
}
#[macro_export]
macro_rules! wre_gl {
() => {
crate::state::WRE_GL.try_lock().unwrap().gl
};
}
|
#![feature(asm)]
use std::fs;
use std::time::{Duration, Instant};
fn read_input(file_name : &str) -> Vec<usize> {
return fs::read_to_string(file_name)
.expect("Failed to read input")
.split('\n')
.filter_map(|x| x.parse::<usize>().ok())
.collect();
}
fn find_solution_naive(rows : &[usize]) -> Option<usize> {
for x in rows {
for y in rows {
for z in rows{
if x != y && x != z && y != z && z + x + y == 2020 {
return Some(x*y*z);
}
}
}
}
None
}
/*
fn find_solution_binary(rows_const : &[usize]) -> Option<usize>{
let mut rows = rows_const.to_owned();
rows.sort_unstable();
for i in 0..rows.len(){
let val = rows[i];
let mut high = rows.len();
let mut low = i;
let mut pivot:usize = (high - low) / 2;
while high > (low+1) {
let pivot_val = rows[pivot];
if val + pivot_val > 2020 {
high = pivot;
}
else if val + pivot_val < 2020 {
low = pivot;
}
else {
return Some(val * pivot_val);
}
pivot = low + (high - low) / 2;
}
}
None
}
*/
fn find_solution_linear(rows_const : &[usize]) -> Option<usize>{
let mut rows = rows_const.to_owned();
rows.sort_unstable();
for i in 0..rows.len() {
let fst = rows[i];
for j in i..rows.len() {
let snd = rows[j] + fst;
for u in j..rows.len(){
if snd + rows[u] == 2020 {
return Some(rows[i]*rows[j]*rows[u])
}
}
}
}
None
}
fn find_solution_asm(rows_const : &[usize]) -> Option<usize>{
let mut rows = rows_const.to_owned();
rows.sort_unstable();
unsafe {
asm!("nop");
}
for i in 0..rows.len() {
let fst = rows[i];
for j in i..rows.len() {
let snd = rows[j] + fst;
for u in j..rows.len(){
if snd + rows[u] == 2020 {
return Some(rows[i]*rows[j]*rows[u])
}
}
}
}
None
}
fn benchmark(name : &str, solver : fn(&[usize]) -> Option<usize>, rows : &[usize]){
let mut avg = 0;
let mut solution = 0;
for i in 0..2000 {
let mut new_rows = rows.clone();
let now = Instant::now();
solution = solver(&mut new_rows).expect("No solution found");
let duration = now.elapsed().as_nanos();
if avg == 0{
avg = duration;
}else{
avg = (avg + duration) / 2;
}
}
println!("Solver {} found: {}, in {} ns",name,solution,avg);
}
fn main() {
let mut rows = read_input("../input");
//benchmark("naive", find_solution_naive, &rows);
//benchmark("binary", find_solution_binary, &rows);
benchmark("linear", find_solution_linear, &rows);
}
|
use std::io::{Read, Result as IOResult};
use crate::lump_data::{LumpData, LumpType};
use crate::PrimitiveRead;
#[derive(Copy, Clone, Debug, Default)]
pub struct Node {
pub plane_number: i32,
pub children: [i32; 2],
pub mins: [i16; 3],
pub maxs: [i16; 3],
pub first_face: u16,
pub faces_count: u16,
pub area: u16,
pub padding: u16,
}
impl LumpData for Node {
fn lump_type() -> LumpType {
LumpType::Nodes
}
fn lump_type_hdr() -> Option<LumpType> {
None
}
fn element_size(_version: i32) -> usize {
32
}
fn read(reader: &mut dyn Read, _version: i32) -> IOResult<Self> {
let plane_number = reader.read_i32()?;
let children: [i32; 2] = [
reader.read_i32()?,
reader.read_i32()?
];
let mins: [i16; 3] = [
reader.read_i16()?,
reader.read_i16()?,
reader.read_i16()?
];
let maxs: [i16; 3] = [
reader.read_i16()?,
reader.read_i16()?,
reader.read_i16()?
];
let first_face = reader.read_u16()?;
let faces_count = reader.read_u16()?;
let area = reader.read_u16()?;
let padding = reader.read_u16()?;
Ok(Self {
plane_number,
children,
mins,
maxs,
first_face,
faces_count,
area,
padding,
})
}
}
|
//use std::time::Duration;
//use std::thread;
//use std::collections::HashSet;
//use std::path::Path;
use sdl2::pixels::Color;
//use sdl2::image::LoadTexture;
use sdl2::render::TextureQuery;
use std::time::Duration;
use std::thread;
//use sdl2::event::Event;
//use sdl2::keyboard::Keycode;
use sdl2::rect::Rect;
const CAM_W: u32 = 1280;
const CAM_H: u32 = 720;
const MESSAGE_TIME: u64 = 500;
fn center(r1: Rect, w: u32, h: u32) -> Rect {
let mut x = r1.x();
let mut y = r1.y();
if r1.width() < w {
x += ((w - r1.width()) / 2) as i32
}
if r1.height() < h {
y += ((h - r1.height()) / 2) as i32
}
Rect::new(x, y, r1.width(), r1.height())
}
fn fit(r1: Rect, w: u32, h: u32) -> Rect {
let c = if w as f32/r1.width() as f32 > h as f32/r1.height() as f32 { // wider
r1.width() as f32 / w as f32
} else {
r1.height() as f32 / h as f32
};
Rect::new(r1.x(), r1.y(), (w as f32 *c) as u32, (h as f32 *c) as u32)
}
pub fn create_attack_tuples<'a, T>(
texture_creator: &'a sdl2::render::TextureCreator<T>,
font: &'a sdl2::ttf::Font,
attack_names: &'a Vec<String>,
attack_effects: &'a Vec<String>,
) -> Result<(Vec<(sdl2::render::Texture<'a>, Rect)>, Vec<(sdl2::render::Texture<'a>, Rect)>), String> {
let rs: Vec<_> = (0..4)
.map(|i| 180 + i * (200 + 40))
.map(|i| Rect::new(i, 560 as i32, 200, 100))
.collect();
let mut attacks_tup = Vec::new();
let mut effects_tup = Vec::new();
for (index, r) in rs.into_iter().enumerate() {
// Create a texture for the name of each attack
let surface = font
.render(&attack_names[index])
.blended(Color::RGB(0xbd, 0xcd, 0xde))
.map_err(|e| e.to_string())?;
let texture = texture_creator
.create_texture_from_surface(&surface)
.map_err(|e| e.to_string())?;
// Figure out how to resize the text to fit within the provided space
let TextureQuery { width, height, .. } = texture.query();
let text_rect = Rect::new(r.x() + 10, r.y() + 5, 180, 50);
let text_rect = center(fit(text_rect, width, height), 180, 50);
// Return the tuple for later use
attacks_tup.push( (texture, text_rect) );
// Create a texture for the effect of each attack
let surface = font
.render(&attack_effects[index])
.blended(Color::RGB(0xbd, 0xcd, 0xde))
.map_err(|e| e.to_string())?;
let texture = texture_creator
.create_texture_from_surface(&surface)
.map_err(|e| e.to_string())?;
// Figure out how to resize the text to fit within the provided space
let TextureQuery { width, height, .. } = texture.query();
let text_rect = Rect::new(r.x() + 10, r.y() + 65, 180, 30);
let text_rect = center(fit(text_rect, width, height), 180, 30);
// Return the tuple for later use
effects_tup.push( (texture, text_rect) );
}
Ok((attacks_tup, effects_tup))
}
pub fn create_name_tuples<'a, T>(
texture_creator: &'a sdl2::render::TextureCreator<T>,
font: &'a sdl2::ttf::Font,
player_monster: &'a String,
enemy_monster: &'a String,
) -> Result<((sdl2::render::Texture<'a>, Rect), (sdl2::render::Texture<'a>, Rect)), String> {
let surface = font
.render(&player_monster)
.blended(Color::BLACK)
.map_err(|e| e.to_string())?;
let player_texture = texture_creator
.create_texture_from_surface(&surface)
.map_err(|e| e.to_string())?;
let TextureQuery { width, height, .. } = player_texture.query();
let text_rect = Rect::new(500, 379, 300, 35);
let text_rect = fit(text_rect, width, height);
let player_rect = Rect::new(500 + (290 - text_rect.width() as i32) as i32, text_rect.y(), text_rect.width(), text_rect.height());
let surface = font
.render(&enemy_monster)
.blended(Color::BLACK)
.map_err(|e| e.to_string())?;
let enemy_texture = texture_creator
.create_texture_from_surface(&surface)
.map_err(|e| e.to_string())?;
let TextureQuery { width, height, .. } = enemy_texture.query();
let text_rect = Rect::new(490, 88, 300, 35);
let enemy_rect = fit(text_rect, width, height);
Ok( ( (player_texture, player_rect), (enemy_texture, enemy_rect) ) )
}
pub struct Battle<'a> {
pub player_name: &'a (sdl2::render::Texture<'a>, Rect),
pub enemy_name: &'a (sdl2::render::Texture<'a>, Rect),
pub background_texture: &'a sdl2::render::Texture<'a>,
pub player_texture: &'a sdl2::render::Texture<'a>,
pub enemy_texture: &'a sdl2::render::Texture<'a>,
pub font: &'a sdl2::ttf::Font<'a, 'a>,
pub player_attacks: &'a Vec<(sdl2::render::Texture<'a>, Rect)>,
pub player_attack_effects: &'a Vec<(sdl2::render::Texture<'a>, Rect)>,
pub player_health: f32,
pub enemy_health: f32,
}
impl<'a> Battle<'a> {
pub fn set_player_health(&mut self, new_health: f32) {
self.player_health = new_health;
}
pub fn set_enemy_health(&mut self, new_health: f32) {
self.enemy_health = new_health;
}
}
pub fn better_draw_battle(wincan: &mut sdl2::render::WindowCanvas, battle_init: &Battle, choice: usize, message: Option<String>) -> Result<(), String> {
// Load the battle scene background
wincan.copy(&battle_init.background_texture, None, Rect::new(0,0,CAM_W,CAM_H))?;
let move_rects: Vec<_> = (0..4)
.map(|i| 180 + i * (200 + 40))
.map(|i| Rect::new(i, 560 as i32, 200, 100))
.collect();
// Create an outline around the move that is currently selected
let outline_size = 5;
let r = move_rects[choice];
let move_outline_rect = Rect::new(r.x() - outline_size, r.y() - outline_size, (r.width() + (2*outline_size)as u32) as u32, (r.height() + (2*outline_size)as u32) as u32);
wincan.set_draw_color(Color::RGB(0xf6, 0x52, 0x41));
wincan.fill_rect(move_outline_rect)?;
// For all moves
for (index, item) in move_rects.into_iter().enumerate() {
// Create the background for each move
let r = item;
wincan.set_draw_color(Color::RGB(0x20, 0x41, 0x6a));
wincan.fill_rect(r)?;
// Add the names of each attack
wincan.copy(&battle_init.player_attacks[index].0, None, battle_init.player_attacks[index].1)?;
// Add the names of each attack
wincan.copy(&battle_init.player_attack_effects[index].0, None, battle_init.player_attack_effects[index].1)?;
}
// Add the names of both monsters
wincan.copy(&battle_init.player_name.0, None, battle_init.player_name.1)?;
wincan.copy(&battle_init.enemy_name.0, None, battle_init.enemy_name.1)?;
// Add both monsters
wincan.copy(&battle_init.player_texture, None, Rect::new(800,275,200,200))?;
wincan.copy_ex(&battle_init.enemy_texture, None, Rect::new(280 as i32,25 as i32,200,200), 0 as f64, None, true, false)?;
// Calculate and add health bars for each monster
health_bars(wincan, battle_init.player_health, battle_init.enemy_health)?;
// FOR DEMO ONLY
let s = vec!["Demo Instructions:","Use AD/←→ to choose a move","Use Enter to submit your choice", "Use K to kill the other monster", "Use E to exit the battle"];
let texture_creator = wincan.texture_creator();
for (index, item) in s.iter().enumerate() {
let surface = battle_init.font
.render(&item)
.blended(Color::BLACK)
.map_err(|e| e.to_string())?;
let texture = texture_creator
.create_texture_from_surface(&surface)
.map_err(|e| e.to_string())?;
let TextureQuery { width, height, .. } = texture.query();
let text_rect = Rect::new(25, 300 + (20*index) as i32, width, 20);
let text_rect = fit(text_rect, width, height);
wincan.copy(&texture, None, text_rect)?;
}
// Print out a message if needed
match message {
Some(text) => {
message_box(wincan, battle_init.font, &text)?;
thread::sleep(Duration::from_millis(MESSAGE_TIME));
},
None => (),
};
wincan.present();
Ok(())
}
pub fn health_bars(wincan: &mut sdl2::render::WindowCanvas, player_health: f32, enemy_health: f32) -> Result<(), String> {
//let enemy_health: f32 = 12 as f32;
if enemy_health > 50 as f32{
wincan.set_draw_color(Color::GREEN);
} else if enemy_health > 20 as f32{
wincan.set_draw_color(Color::YELLOW);
} else if enemy_health == 0 as f32 {
wincan.set_draw_color(Color::RGBA(0,0,0,0));
} else {
wincan.set_draw_color(Color::RED);
}
let r2 = Rect::new(508, 54, ((enemy_health*435.0/100.0) as f32).ceil() as u32, 18);
wincan.fill_rect(r2)?;
// let r2 = Rect::new(333, 429, 435, 18);
// let player_health: f32 = 51 as f32;
if player_health > 50 as f32{
wincan.set_draw_color(Color::GREEN);
} else if player_health > 20 as f32{
wincan.set_draw_color(Color::YELLOW);
} else if player_health == 0 as f32 {
wincan.set_draw_color(Color::RGBA(0,0,0,0));
} else {
wincan.set_draw_color(Color::RED);
}
let r2 = Rect::new(333, 429, ((player_health*435.0/100.0) as f32).ceil() as u32, 18);
wincan.fill_rect(r2)?;
// wincan.present();
Ok(())
}
fn message_box<'a>(
wincan: &mut sdl2::render::WindowCanvas,
font: &'a sdl2::ttf::Font,
message: &str,
) -> Result<(), String> {
let texture_creator = wincan.texture_creator();
let r2 = Rect::new(600, 150, 400, 125);
wincan.set_draw_color(Color::WHITE);
wincan.fill_rect(r2)?;
let r2 = Rect::new(605, 155, 390, 115);
wincan.set_draw_color(Color::BLACK);
wincan.fill_rect(r2)?;
let r2 = Rect::new(610, 160, 380, 105);
wincan.set_draw_color(Color::WHITE);
wincan.fill_rect(r2)?;
let mut line_message = format!("");
let mut line_number = 0;
for c in message.chars() {
line_message = format!("{}{}", line_message, c);
let mut surface = font
.render(&line_message)
.blended(Color::BLACK)
.map_err(|e| e.to_string())?;
let mut texture = texture_creator
.create_texture_from_surface(&surface)
.map_err(|e| e.to_string())?;
let TextureQuery { width, height, .. } = texture.query();
if width as f32/height as f32 > 375 as f32/30 as f32 {
line_number += 1;
line_message = format!("{}", c);
surface = font
.render(&line_message)
.blended(Color::BLACK)
.map_err(|e| e.to_string())?;
texture = texture_creator
.create_texture_from_surface(&surface)
.map_err(|e| e.to_string())?;
}
let TextureQuery { width, height, .. } = texture.query();
let text_rect = Rect::new(612, 162 + (line_number * 35), 375, 30);
let text_rect = fit(text_rect, width, height);
wincan.copy(&texture, None, text_rect)?;
wincan.present();
}
Ok(())
} |
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let k: usize = rd.get();
let n: usize = rd.get();
let m: usize = rd.get();
let a: Vec<usize> = rd.get_vec(n);
let mut d: Vec<usize> = a.windows(2).map(|w| w[1] - w[0] - 1).collect();
d.sort();
let mut cum = vec![0; n];
for i in 1..n {
cum[i] = cum[i - 1] + d[i - 1];
}
for _ in 0..m {
let x: usize = rd.get();
let y: usize = rd.get();
if n == 1 {
let ans = x.min(a[0] - 1) + y.min(k - a[0]) + 1;
println!("{}", ans);
} else {
let z = y + x;
let c = d.upper_bound(&z);
let ans = cum[c] + (n - 1 - c) * z + x.min(a[0] - 1) + y.min(k - a[n - 1]) + n;
println!("{}", ans);
}
}
}
pub trait BinarySearch<T> {
fn lower_bound(&self, x: &T) -> usize;
fn upper_bound(&self, x: &T) -> usize;
fn split_by(
&self,
x: &T,
) -> (
std::ops::Range<usize>,
std::ops::Range<usize>,
std::ops::Range<usize>,
);
}
impl<T: Ord> BinarySearch<T> for [T] {
fn lower_bound(&self, x: &T) -> usize {
if self[0].ge(x) {
return 0;
}
let mut lf = 0;
let mut rg = self.len();
while rg - lf > 1 {
let md = (rg + lf) / 2;
if self[md].lt(x) {
lf = md;
} else {
rg = md;
}
}
rg
}
fn upper_bound(&self, x: &T) -> usize {
if self[0].gt(x) {
return 0;
}
let mut lf = 0;
let mut rg = self.len();
while rg - lf > 1 {
let md = (rg + lf) / 2;
if self[md].le(x) {
lf = md;
} else {
rg = md;
}
}
rg
}
fn split_by(
&self,
x: &T,
) -> (
std::ops::Range<usize>,
std::ops::Range<usize>,
std::ops::Range<usize>,
) {
let i = self.lower_bound(x);
let j = self.upper_bound(x);
(0..i, i..j, j..self.len())
}
}
pub struct ProconReader<R> {
r: R,
l: String,
i: usize,
}
impl<R: std::io::BufRead> ProconReader<R> {
pub fn new(reader: R) -> Self {
Self {
r: reader,
l: String::new(),
i: 0,
}
}
pub fn get<T>(&mut self) -> T
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Debug,
{
self.skip_blanks();
assert!(self.i < self.l.len()); // remain some character
assert_ne!(&self.l[self.i..=self.i], " ");
let rest = &self.l[self.i..];
let len = rest.find(' ').unwrap_or_else(|| rest.len());
// parse self.l[self.i..(self.i + len)]
let val = rest[..len]
.parse()
.unwrap_or_else(|e| panic!("{:?}, attempt to read `{}`", e, rest));
self.i += len;
val
}
fn skip_blanks(&mut self) {
loop {
match self.l[self.i..].find(|ch| ch != ' ') {
Some(j) => {
self.i += j;
break;
}
None => {
let mut buf = String::new();
let num_bytes = self
.r
.read_line(&mut buf)
.unwrap_or_else(|_| panic!("invalid UTF-8"));
assert!(num_bytes > 0, "reached EOF :(");
self.l = buf
.trim_end_matches('\n')
.trim_end_matches('\r')
.to_string();
self.i = 0;
}
}
}
}
pub fn get_vec<T>(&mut self, n: usize) -> Vec<T>
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Debug,
{
(0..n).map(|_| self.get()).collect()
}
pub fn get_chars(&mut self) -> Vec<char> {
self.get::<String>().chars().collect()
}
}
|
use std::io::TcpStream;
use std::io;
use std::sync::mpsc::channel;
pub fn start() {
let username = ask_username();
let mut reader = io::stdin();
let mut stream = TcpStream::connect("0.0.0.0:6262");
let (sender, receiver) = channel();
Thread::spawn(move || send_messages(sender));
Thread::scoped(move || accept_messages())
}
// loop {
// let mut msg = reader.read_line().ok().expect("Error reading your message");
// msg.pop();
// println!("sending: {}", msg);
// stream.write(msg.as_bytes());
// stream.flush().ok();
// }
fn ask_username() -> String {
print!("Choose a username: ");
let mut reader = io::stdin();
let mut username = reader.read_line().ok().expect("Error while reading username");
username.pop();
username
}
|
#![warn(unused_crate_dependencies)]
#![allow(clippy::derive_partial_eq_without_eq)]
// Workaround for "unused crate" lint false positives.
use workspace_hack as _;
pub mod proto {
tonic::include_proto!("test");
}
pub use proto::*;
|
pub mod runtime;
#[macro_export]
macro_rules! declare_plugin {
($plugin_type:ty, $constructor:path) => {
#[no_mangle]
pub extern "C" fn _plugin_create() -> *mut $crate::plugins::runtime::RuntimePlugin {
// make sure the constructor is the correct type.
let constructor: fn() -> $plugin_type = $constructor;
let object = constructor();
let boxed: Box<$crate::plugins::runtime::RuntimePlugin> = Box::new(object);
Box::into_raw(boxed)
}
};
}
|
use serde::Serialize;
use domain_patterns::event::DomainEvent;
use domain_patterns::message::Message;
use domain_patterns::models::{Entity, AggregateRoot};
use uuid::Uuid;
use crate::survey::Survey;
#[derive(DomainEvent, Serialize)]
pub struct SurveyCreatedEvent {
pub id: String,
pub aggregate_id: String,
pub version: u64,
pub occurred: i64,
pub author: String,
pub title: String,
pub description: String,
pub category: String,
pub questions: Vec<QuestionCreatedEvent>
}
#[derive(Serialize)]
pub struct QuestionCreatedEvent {
pub id: String,
pub question_type: String,
pub title: String,
pub choices: Vec<ChoiceCreatedEvent>
}
#[derive(Serialize)]
pub struct ChoiceCreatedEvent {
pub id: String,
pub content: Option<String>,
pub content_type: String,
pub title: String,
}
impl From<&Survey> for SurveyCreatedEvent {
fn from(survey: &Survey) -> Self {
let questions: Vec<QuestionCreatedEvent> = survey.questions.iter().map(|q| {
QuestionCreatedEvent {
id: q.id.to_string(),
question_type: q.kind.to_string(),
title: q.title().to_string(),
choices: q.choices.iter().map(|c|{
let content = if let Some(c) = &c.content {
Some(c.to_string())
} else {
None
};
ChoiceCreatedEvent {
id: c.id.to_string(),
content,
content_type: c.content_type.to_string(),
title: c.title.to_string(),
}
}).collect(),
}
}).collect();
SurveyCreatedEvent {
id: Uuid::new_v4().to_string(),
aggregate_id: survey.id(),
version: survey.version(),
occurred: survey.created_on,
author: survey.author.to_string(),
title: survey.title.to_string(),
description: survey.description.to_string(),
category: survey.category.to_string(),
questions,
}
}
}
#[derive(DomainEvent, Serialize)]
pub struct SurveyUpdatedEvent {
pub id: String,
pub aggregate_id: String,
pub version: u64,
pub occurred: i64,
pub title: Option<String>,
pub description: Option<String>,
pub category: Option<String>,
pub questions: Option<Vec<QuestionUpdatedEvent>>,
}
#[derive(Serialize)]
pub struct QuestionUpdatedEvent {
pub id: String,
pub question_type: Option<String>,
pub title: Option<String>,
pub choices: Option<Vec<ChoiceUpdatedEvent>>,
}
#[derive(Serialize)]
pub struct ChoiceUpdatedEvent {
pub id: String,
// Empty string if None. Think about changing this? not sure on this one.
pub content: Option<Option<String>>,
pub content_type: Option<String>,
pub title: Option<String>,
}
#[derive(DomainEvents)]
pub enum SurveyEvents {
SurveyCreatedEvent(SurveyCreatedEvent),
SurveyUpdatedEvent(SurveyUpdatedEvent),
}
|
use std::io;
pub struct Operator {}
impl Operator {
pub fn add(x: i32, y: i32) -> i32 {
x + y
}
pub fn multiply(x: i32, y: i32) -> i32 {
x * y
}
pub fn input() -> i32 {
println!("Provide input: ");
let mut input = String::new();
io::stdin().read_line(&mut input)
.expect(":(");
input.trim().parse().expect("invalid input")
}
pub fn output(x: i32) -> i32 {
x
}
}
|
// This module provides the fallback implementation of mmap primitives on platforms which do not provide them
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
mod fallback {
use alloc::alloc::{AllocError, Layout};
use core::ptr::NonNull;
use firefly_system::arch as sys;
/// Creates a memory mapping for the given `Layout`
#[inline]
pub unsafe fn map(layout: Layout) -> Result<NonNull<u8>, AllocError> {
sys::alloc::allocate(layout).map(|ptr| ptr.cast())
}
/// Creates a memory mapping specifically set up to behave like a stack
///
/// NOTE: This is a fallback implementation, so no guard page is present,
/// and it is implemented on top of plain `map`
#[inline]
pub unsafe fn map_stack(pages: usize) -> Result<NonNull<u8>, AllocError> {
let page_size = sys::mem::page_size();
let layout = Layout::from_size_align(page_size * pages, page_size).unwrap();
sys::alloc::allocate(layout).map(|ptr| ptr.cast())
}
/// Remaps a mapping given a pointer to the mapping, the layout which created it, and the new size
#[inline]
pub unsafe fn remap(
ptr: *mut u8,
old_layout: Layout,
new_size: usize,
) -> Result<NonNull<u8>, AllocError> {
let new_layout =
Layout::from_size_align(new_size, old_layout.align()).map_err(|_| AllocError)?;
let ptr = NonNull::new(ptr).ok_or(AllocError)?;
if old_layout.size() < new_size {
sys::alloc::grow(ptr, old_layout, new_layout)
} else {
sys::alloc::shrink(ptr, old_layout, new_layout)
}
.map(|ptr| ptr.cast())
}
/// Destroys a mapping given a pointer to the mapping and the layout which created it
#[inline]
pub unsafe fn unmap(ptr: *mut u8, layout: Layout) {
if ptr.is_null() {
return;
}
sys::alloc::deallocate(NonNull::new_unchecked(ptr), layout);
}
}
// This module provides the real implementation of mmap primitives on platforms which provide them
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
mod real {
use alloc::alloc::{AllocError, Layout};
use core::ptr::NonNull;
use firefly_system::arch as sys;
/// Creates a memory mapping for the given `Layout`
#[inline]
pub unsafe fn map(layout: Layout) -> Result<NonNull<u8>, AllocError> {
sys::mmap::map(layout).map(|(ptr, _)| ptr)
}
/// Creates a memory mapping specifically set up to behave like a stack
#[inline]
pub unsafe fn map_stack(pages: usize) -> Result<NonNull<u8>, AllocError> {
sys::mmap::map_stack(pages)
}
/// Remaps a mapping given a pointer to the mapping, the layout which created it, and the new size
#[inline]
pub unsafe fn remap(
ptr: *mut u8,
layout: Layout,
new_size: usize,
) -> Result<NonNull<u8>, AllocError> {
sys::mmap::remap(ptr, layout, new_size).map(|(ptr, _)| ptr)
}
/// Destroys a mapping given a pointer to the mapping and the layout which created it
#[inline]
pub unsafe fn unmap(ptr: *mut u8, layout: Layout) {
sys::mmap::unmap(ptr, layout);
}
}
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
pub use self::fallback::*;
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
pub use self::real::*;
|
use crate::config::{
CameraConfig, DatastructureConfig, GeneralConfig, GeneratorConfig, RaytracerConfig,
ShaderConfig,
};
use crate::util::vector::Vector;
impl Default for GeneralConfig {
fn default() -> Self {
Self {
epsilon: 0.00001,
scenename: "test".to_string(),
outputname: "render.bmp".to_string(),
texturepath: "scenes".to_string(),
}
}
}
impl Default for CameraConfig {
fn default() -> Self {
Self {
position: Vector::default(),
direction: Vector::new(0.0,0.0,-1.0),
width: 1000,
height: 1000,
fov: 60.,
}
}
}
impl Default for DatastructureConfig {
fn default() -> Self {
DatastructureConfig::kdtree
}
}
impl Default for ShaderConfig {
fn default() -> Self {
ShaderConfig::vmcshader {
air_density: 0.3,
particle_reflectivity: 0.4,
}
}
}
impl Default for RaytracerConfig {
fn default() -> Self {
RaytracerConfig::basic
}
}
impl Default for GeneratorConfig {
fn default() -> Self {
GeneratorConfig::basic
}
}
|
pub struct Solution;
impl Solution {
pub fn reverse_string(s: &mut Vec<char>) {
s.reverse();
}
}
#[test]
fn test0344() {
fn case(s: &str, want: &str) {
let mut s = s.chars().collect::<Vec<char>>();
Solution::reverse_string(&mut s);
let want = want.chars().collect::<Vec<char>>();
assert_eq!(s, want);
}
case("hello", "olleh");
case("Hannah", "hannaH");
}
|
/*
UTF-8 中的一个字符可能的长度为 1 到 4 字节,遵循以下的规则:
对于 1 字节的字符,字节的第一位设为0,后面7位为这个符号的unicode码。
对于 n 字节的字符 (n > 1),第一个字节的前 n 位都设为1,第 n+1 位设为0,后面字节的前两位一律设为10。剩下的没有提及的二进制位,全部为这个符号的unicode码。
这是 UTF-8 编码的工作方式:
Char. number range | UTF-8 octet sequence
(hexadecimal) | (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
给定一个表示数据的整数数组,返回它是否为有效的 utf-8 编码。
注意:
输入是整数数组。只有每个整数的最低 8 个有效位用来存储数据。这意味着每个整数只表示 1 字节的数据。
示例 1:
data = [197, 130, 1], 表示 8 位的序列: 11000101 10000010 00000001.
返回 true 。
这是有效的 utf-8 编码,为一个2字节字符,跟着一个1字节字符。
示例 2:
data = [235, 140, 4], 表示 8 位的序列: 11101011 10001100 00000100.
返回 false 。
前 3 位都是 1 ,第 4 位为 0 表示它是一个3字节字符。
下一个字节是开头为 10 的延续字节,这是正确的。
但第二个延续字节不以 10 开头,所以是不符合规则的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/utf-8-validation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
fn main() {
let data = vec![235, 140, 4];
let is_utf8 = Solution::valid_utf8(data);
dbg!(is_utf8);
let data = vec![197, 130, 1];
let is_utf8 = Solution::valid_utf8(data);
dbg!(is_utf8);
}
struct Solution {}
impl Solution {
#[allow(unused_parens)]
pub fn valid_utf8(data: Vec<i32>) -> bool {
let data: Vec<_> = data.iter().map(|it| *it as u8).collect();
dbg!(&data);
let mut i = 0;
'outer: while i < data.len() {
let byte = data[i];
if byte & 0b1000_0000 == 0 {
// 第一个字节为 0XXX_XXXX型 单字节字符
i += 1;
continue;
}
if byte & 0b0100_0000 == 0 {
// 第一个字节为 10XX_XXXX型 不是utf8编码
return false;
}
for n in 1..4 {
// 到这里来了至少是双字节字符
if i + n >= data.len() {
return false;
}
if (data[i + n] >> 6) != 0b10 {
return false;
}
if byte & (0b1000_0000 >> (n + 1)) as u8 == 0 {
// 第一个字节为 110X_XXXX型
i += (n + 1);
continue 'outer;
}
}
return false;
}
return true;
}
}
|
pub struct LinearMemory {
// linear because it gets treated as one continuous address space
pub data: Vec<u8>,
}
impl LinearMemory {
pub fn get(&self, a: u16) -> u8 {
self.data[usize::from(a)]
}
pub fn set(&mut self, a: u16, v: u8) {
self.data[usize::from(a)] = v
}
pub fn get_word(&mut self, a: u16) -> u16 {
println!("{:#015b}", u16::from(self.get(a)));
println!("{:#015b}", (u16::from(self.get(a + 1)) << 8));
println!("{:#015b}", u16::from(self.get(a)) | (u16::from(self.get(a + 1)) << 8));
u16::from(self.get(a)) | (u16::from(self.get(a + 1)) << 8)
// makes a u16 out of the variable
// then does a logical or with the next byte bit shifted by 8.
// remember, logical or compares the bits on both numbers, and puts a 1 in the result if either have a 1
// eg: a = 0b0000011010100
// b = 0b1100000000000
// result = 0b1100011010100
// why bitwise or?
// why do we bitshift it by 8 bits (1 byte) to the left?
// bitshift to the left is like a multiply, to the right is like divide.
//
}
pub fn set_word() {
}
pub fn new() -> Self {
Self {data: vec![0; 65536]}
}
}
// usize is a pointer sized unsigned integer type.
// the size is how many bytes it takes to ref a particular location in memory. |
use std::any::Any;
use std::cell::{RefCell, RefMut};
type VO<T> = Vec<Option<T>>;
#[derive(Default)]
pub struct World {
entities_count: usize,
components_vec_list: Vec<Box<dyn ComponentVec>>,
}
impl World {
pub fn new() -> Self {
Self {
entities_count: 0,
components_vec_list: vec![],
}
}
pub fn new_entity(&mut self) -> usize {
let entity_id = self.entities_count;
self.components_vec_list
.iter_mut()
.for_each(|component_vec| {
component_vec.push_none();
});
self.entities_count += 1;
entity_id
}
pub fn add_component_to_entity<ComponentType: 'static>(
&mut self,
entity_id: usize,
component: ComponentType,
) {
for component_vec in self.components_vec_list.iter_mut() {
if let Some(component_vec) = component_vec
.as_any_mut()
.downcast_mut::<Vec<Option<ComponentType>>>()
{
component_vec[entity_id] = Some(component);
return;
};
}
let mut new_component_vec: Vec<Option<ComponentType>> =
Vec::with_capacity(self.entities_count);
for _ in 0..self.entities_count {
new_component_vec.push(None);
}
new_component_vec[entity_id] = Some(component);
self.components_vec_list
.push(Box::new(RefCell::new(new_component_vec)));
}
pub fn borrow_component_vec_mut<ComponentType: 'static>(
&self,
) -> Option<RefMut<VO<ComponentType>>> {
for component_vec in self.components_vec_list.iter() {
if let Some(component_vec) = component_vec
.as_any()
.downcast_ref::<RefCell<VO<ComponentType>>>()
{
return Some(component_vec.borrow_mut());
}
}
None
}
}
trait ComponentVec {
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
fn push_none(&mut self);
}
impl<T: 'static> ComponentVec for RefCell<VO<T>> {
fn as_any(&self) -> &dyn Any {
self as &dyn Any
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self as &mut dyn Any
}
fn push_none(&mut self) {
self.get_mut().push(None);
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::any::Any;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::sync::Arc;
use common_base::runtime::execute_futures_in_parallel;
use common_catalog::table_context::TableContext;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::BlockThresholds;
use common_expression::DataBlock;
use common_expression::TableSchemaRef;
use opendal::Operator;
use storages_common_cache::CacheAccessor;
use storages_common_cache_manager::CacheManager;
use storages_common_table_meta::meta::BlockMeta;
use storages_common_table_meta::meta::Location;
use storages_common_table_meta::meta::SegmentInfo;
use storages_common_table_meta::meta::Statistics;
use crate::io::SegmentsIO;
use crate::io::TableMetaLocationGenerator;
use crate::operations::mutation::AbortOperation;
use crate::operations::mutation::Mutation;
use crate::operations::mutation::MutationSinkMeta;
use crate::operations::mutation::MutationTransformMeta;
use crate::pipelines::processors::port::InputPort;
use crate::pipelines::processors::port::OutputPort;
use crate::pipelines::processors::processor::Event;
use crate::pipelines::processors::processor::ProcessorPtr;
use crate::pipelines::processors::Processor;
use crate::statistics::reducers::merge_statistics_mut;
use crate::statistics::reducers::reduce_block_metas;
type MutationMap = HashMap<usize, (Vec<(usize, Arc<BlockMeta>)>, Vec<usize>)>;
struct SerializedData {
data: Vec<u8>,
location: String,
segment: Arc<SegmentInfo>,
}
enum State {
None,
GatherMeta(DataBlock),
ReadSegments,
GenerateSegments(Vec<Arc<SegmentInfo>>),
SerializedSegments {
serialized_data: Vec<SerializedData>,
segments: Vec<Location>,
summary: Statistics,
},
Output {
segments: Vec<Location>,
summary: Statistics,
},
}
pub struct MutationTransform {
state: State,
ctx: Arc<dyn TableContext>,
schema: TableSchemaRef,
dal: Operator,
location_gen: TableMetaLocationGenerator,
base_segments: Vec<Location>,
thresholds: BlockThresholds,
abort_operation: AbortOperation,
inputs: Vec<Arc<InputPort>>,
input_metas: MutationMap,
cur_input_index: usize,
output: Arc<OutputPort>,
output_data: Option<DataBlock>,
}
impl MutationTransform {
#[allow(clippy::too_many_arguments)]
pub fn try_create(
ctx: Arc<dyn TableContext>,
schema: TableSchemaRef,
inputs: Vec<Arc<InputPort>>,
output: Arc<OutputPort>,
dal: Operator,
location_gen: TableMetaLocationGenerator,
base_segments: Vec<Location>,
thresholds: BlockThresholds,
) -> Result<ProcessorPtr> {
Ok(ProcessorPtr::create(Box::new(MutationTransform {
state: State::None,
ctx,
schema,
dal,
location_gen,
base_segments,
thresholds,
abort_operation: AbortOperation::default(),
inputs,
input_metas: HashMap::new(),
cur_input_index: 0,
output,
output_data: None,
})))
}
fn get_current_input(&mut self) -> Option<Arc<InputPort>> {
let mut finished = true;
let mut index = self.cur_input_index;
loop {
let input = &self.inputs[index];
if !input.is_finished() {
finished = false;
input.set_need_data();
if input.has_data() {
self.cur_input_index = index;
return Some(input.clone());
}
}
index += 1;
if index == self.inputs.len() {
index = 0;
}
if index == self.cur_input_index {
return match finished {
true => Some(input.clone()),
false => None,
};
}
}
}
async fn write_segments(&self, segments: Vec<SerializedData>) -> Result<()> {
let mut tasks = Vec::with_capacity(segments.len());
for segment in segments {
let op = self.dal.clone();
tasks.push(async move {
op.write(&segment.location, segment.data).await?;
if let Some(segment_cache) = CacheManager::instance().get_table_segment_cache() {
segment_cache.put(segment.location.clone(), segment.segment.clone());
}
Ok::<_, ErrorCode>(())
});
}
let threads_nums = self.ctx.get_settings().get_max_threads()? as usize;
let permit_nums = self.ctx.get_settings().get_max_storage_io_requests()? as usize;
execute_futures_in_parallel(
tasks,
threads_nums,
permit_nums,
"mutation-write-segments-worker".to_owned(),
)
.await?
.into_iter()
.collect::<Result<Vec<_>>>()?;
Ok(())
}
}
#[async_trait::async_trait]
impl Processor for MutationTransform {
fn name(&self) -> String {
"MutationTransform".to_string()
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
fn event(&mut self) -> Result<Event> {
if matches!(
self.state,
State::GenerateSegments(_) | State::Output { .. }
) {
return Ok(Event::Sync);
}
if matches!(self.state, State::SerializedSegments { .. }) {
return Ok(Event::Async);
}
if self.output.is_finished() {
for input in &self.inputs {
input.finish();
}
return Ok(Event::Finished);
}
if !self.output.can_push() {
return Ok(Event::NeedConsume);
}
if let Some(data_block) = self.output_data.take() {
self.output.push_data(Ok(data_block));
return Ok(Event::NeedConsume);
}
let current_input = self.get_current_input();
if let Some(cur_input) = current_input {
if cur_input.is_finished() {
self.state = State::ReadSegments;
return Ok(Event::Async);
}
self.state = State::GatherMeta(cur_input.pull_data().unwrap()?);
cur_input.set_need_data();
return Ok(Event::Sync);
}
Ok(Event::NeedData)
}
fn process(&mut self) -> Result<()> {
match std::mem::replace(&mut self.state, State::None) {
State::GatherMeta(input) => {
let input_meta = input
.get_meta()
.cloned()
.ok_or_else(|| ErrorCode::Internal("No block meta. It's a bug"))?;
let meta = MutationTransformMeta::from_meta(&input_meta)?;
match &meta.op {
Mutation::Replaced(block_meta) => {
self.input_metas
.entry(meta.index.segment_idx)
.and_modify(|v| v.0.push((meta.index.block_idx, block_meta.clone())))
.or_insert((vec![(meta.index.block_idx, block_meta.clone())], vec![]));
self.abort_operation.add_block(block_meta);
}
Mutation::Deleted => {
self.input_metas
.entry(meta.index.segment_idx)
.and_modify(|v| v.1.push(meta.index.block_idx))
.or_insert((vec![], vec![meta.index.block_idx]));
}
Mutation::DoNothing => (),
}
}
State::GenerateSegments(segment_infos) => {
let segments = self.base_segments.clone();
let mut summary = Statistics::default();
let mut serialized_data = Vec::with_capacity(self.input_metas.len());
let mut segments_editor =
BTreeMap::<_, _>::from_iter(segments.into_iter().enumerate());
for (seg_idx, seg_info) in segment_infos.iter().enumerate() {
if let Some((replaced, deleted)) = self.input_metas.get(&seg_idx) {
// prepare the new segment
let mut new_segment =
SegmentInfo::new(seg_info.blocks.clone(), seg_info.summary.clone());
// take away the blocks, they are being mutated
let mut block_editor = BTreeMap::<_, _>::from_iter(
std::mem::take(&mut new_segment.blocks)
.into_iter()
.enumerate(),
);
for (idx, new_meta) in replaced {
block_editor.insert(*idx, new_meta.clone());
}
for idx in deleted {
block_editor.remove(idx);
}
// assign back the mutated blocks to segment
new_segment.blocks = block_editor.into_values().collect();
if new_segment.blocks.is_empty() {
segments_editor.remove(&seg_idx);
} else {
// re-calculate the segment statistics
let new_summary =
reduce_block_metas(&new_segment.blocks, self.thresholds)?;
merge_statistics_mut(&mut summary, &new_summary)?;
new_segment.summary = new_summary;
let location = self.location_gen.gen_segment_info_location();
self.abort_operation.add_segment(location.clone());
segments_editor
.insert(seg_idx, (location.clone(), new_segment.format_version()));
serialized_data.push(SerializedData {
data: serde_json::to_vec(&new_segment)?,
location,
segment: Arc::new(new_segment),
});
}
} else {
merge_statistics_mut(&mut summary, &seg_info.summary)?;
}
}
// assign back the mutated segments to snapshot
let segments = segments_editor.into_values().collect();
self.state = State::SerializedSegments {
serialized_data,
segments,
summary,
};
}
State::Output { segments, summary } => {
let meta = MutationSinkMeta::create(
segments,
summary,
std::mem::take(&mut self.abort_operation),
);
self.output_data = Some(DataBlock::empty_with_meta(meta));
}
_ => return Err(ErrorCode::Internal("It's a bug.")),
}
Ok(())
}
async fn async_process(&mut self) -> Result<()> {
match std::mem::replace(&mut self.state, State::None) {
State::ReadSegments => {
// Read all segments information in parallel.
let segments_io =
SegmentsIO::create(self.ctx.clone(), self.dal.clone(), self.schema.clone());
let segment_locations = self.base_segments.as_slice();
let segments = segments_io
.read_segments(segment_locations)
.await?
.into_iter()
.collect::<Result<Vec<_>>>()?;
self.state = State::GenerateSegments(segments);
}
State::SerializedSegments {
serialized_data,
segments,
summary,
} => {
self.write_segments(serialized_data).await?;
self.state = State::Output { segments, summary };
}
_ => return Err(ErrorCode::Internal("It's a bug.")),
}
Ok(())
}
}
|
use std::collections::HashMap;
use std::path::Path;
use mail::{Resource, Context};
use mail::file_buffer::FileBuffer;
use template::TemplateEngine;
use template::{
EmbeddedWithCId,
BodyPart, MailParts
};
use ::error::{LoadingError, InsertionError};
use ::utils::fix_newlines;
use ::spec::TemplateSpec;
use ::traits::{RenderEngine, RenderEngineBase, AdditionalCIds};
use ::settings::LoadSpecSettings;
#[derive(Debug)]
pub struct RenderTemplateEngine<R>
where R: RenderEngineBase
{
fix_newlines: bool,
render_engine: R,
id2spec: HashMap<String, TemplateSpec>,
}
impl<R> RenderTemplateEngine<R>
where R: RenderEngineBase
{
pub fn new(render_engine: R) -> Self {
RenderTemplateEngine {
render_engine,
id2spec: Default::default(),
fix_newlines: !R::PRODUCES_VALID_NEWLINES,
}
}
pub fn set_fix_newlines(&mut self, should_fix_newlines: bool) {
self.fix_newlines = should_fix_newlines
}
pub fn does_fix_newlines(&self) -> bool {
self.fix_newlines
}
/// add a `TemplateSpec`, loading all templates in it
///
/// If a template with the same name is contained it
/// will be removed (and unloaded and returned).
///
/// If a template replaces a new template the old
/// template is first unloaded and then the new
/// template is loaded.
///
/// # Error
///
/// If the render templates where already loaded or can not
/// be loaded an error is returned.
///
/// If an error occurs when loading a new spec which _replaces_
/// an old spec the old spec is already removed and unloaded.
/// I.e. it's guaranteed that if `insert` errors there will no
/// longer be an template associated with the given id.
///
pub fn insert_spec(
&mut self,
id: String,
spec: TemplateSpec
) -> Result<Option<TemplateSpec>, InsertionError<R::LoadingError>> {
use std::collections::hash_map::Entry::*;
match self.id2spec.entry(id) {
Occupied(mut entry) => {
let old = entry.insert(spec);
self.render_engine.unload_templates(&old);
let res = self.render_engine.load_templates(entry.get());
if let Err(error) = res {
let (_, failed_new_value) = entry.remove_entry();
Err(InsertionError {
error, failed_new_value,
old_value: Some(old)
})
} else {
Ok(Some(old))
}
},
Vacant(entry) => {
let res = self.render_engine.load_templates(&spec);
if let Err(error) = res {
Err(InsertionError {
error, failed_new_value: spec,
old_value: None
})
} else {
entry.insert(spec);
Ok(None)
}
}
}
}
/// removes and unload the spec associated with the given id
///
/// If no spec is associated with the given id nothing is done
/// (and `None` is returned).
pub fn remove_spec(&mut self, id: &str) -> Option<TemplateSpec> {
let res = self.id2spec.remove(id);
if let Some(spec) = res.as_ref() {
self.render_engine.unload_templates(spec);
}
res
}
pub fn specs(&self) -> &HashMap<String, TemplateSpec> {
&self.id2spec
}
pub fn specs_mut(&mut self) -> impl Iterator<Item=(&String, &mut TemplateSpec)> {
self.id2spec.iter_mut()
}
pub fn lookup_spec(&self, template_id: &str) -> Option<&TemplateSpec> {
self.id2spec.get(template_id)
}
/// each folder in `templates_dir` is seen as a TemplateSpec
///
/// # Error
///
/// If an error can occur when creating the spec(s), or when inserting/using
/// them. If such an error occurs all previously added Spec are not removed,
/// i.e. if an error happens some spec and embeddings might be added others
/// might not.
pub fn load_templates(
&mut self,
templates_dir: impl AsRef<Path>,
settings: &LoadSpecSettings
) -> Result<(), LoadingError<R::LoadingError>> {
for (name, spec) in TemplateSpec::from_dirs(templates_dir.as_ref(), settings)? {
self.insert_spec(name, spec)?;
}
Ok(())
}
}
impl<C, D, R> TemplateEngine<C, D> for RenderTemplateEngine<R>
where C: Context, R: RenderEngine<D>
{
type TemplateId = str;
type Error = <R as RenderEngineBase>::RenderError;
fn use_template(
&self,
template_id: &str,
data: &D,
ctx: &C,
) -> Result<MailParts, Self::Error >
{
let spec = self.lookup_spec(template_id)
.ok_or_else(|| R::unknown_template_id_error(template_id))?;
//OPTIMIZE there should be a more efficient way
// maybe use Rc<str> as keys? and Rc<Resource> for embeddings?
let shared_embeddings = spec.embeddings().iter()
.map(|(key, resource)| create_embedding(key, resource, ctx))
.collect::<HashMap<_,_>>();
let bodies = spec.sub_specs().try_mapped_ref(|sub_spec| {
let embeddings = sub_spec.embeddings().iter()
.map(|(key, resource)| create_embedding(key, resource, ctx))
.collect::<HashMap<_,_>>();
let rendered = {
let embeddings = &[&embeddings, &shared_embeddings];
let additional_cids = AdditionalCIds::new(embeddings);
self.render_engine.render(sub_spec, data, additional_cids)?
};
let rendered =
if self.fix_newlines {
fix_newlines(rendered)
} else {
rendered
};
let buffer = FileBuffer::new(sub_spec.media_type().clone(), rendered.into());
let resource = Resource::sourceless_from_buffer(buffer);
Ok(BodyPart {
resource: resource,
embeddings: embeddings.into_iter().map(|(_,v)| v).collect()
})
})?;
let attachments = spec.attachments().iter()
.map(|resource| EmbeddedWithCId::attachment(resource.clone(), ctx))
.collect();
Ok(MailParts {
alternative_bodies: bodies,
//TODO collpas embeddings and attachments and use their disposition parma
// instead
shared_embeddings: shared_embeddings.into_iter().map(|(_, v)| v).collect(),
attachments,
})
}
}
fn create_embedding(
key: &str,
resource: &Resource,
ctx: &impl Context
) -> (String, EmbeddedWithCId)
{
(key.to_owned(), EmbeddedWithCId::inline(resource.clone(), ctx))
} |
use std::env;
use crate::commands::{LllCommand, LllRunnable};
use crate::context::LllContext;
use crate::error::LllError;
use crate::ui;
use crate::window::LllView;
#[derive(Clone, Debug)]
pub struct TabSwitch {
movement: i32,
}
impl TabSwitch {
pub fn new(movement: i32) -> Self {
TabSwitch { movement }
}
pub const fn command() -> &'static str {
"tab_switch"
}
pub fn tab_switch(
new_index: usize,
context: &mut LllContext,
view: &LllView,
) -> std::io::Result<()> {
context.curr_tab_index = new_index;
let path = &context.curr_tab_ref().curr_path;
env::set_current_dir(path)?;
{
let curr_tab = &mut context.tabs[context.curr_tab_index];
if curr_tab.curr_list.need_update() {
curr_tab
.curr_list
.update_contents(&context.config_t.sort_option)?;
}
curr_tab.refresh(view, &context.config_t);
}
ui::redraw_tab_view(&view.tab_win, &context);
ncurses::doupdate();
Ok(())
}
}
impl LllCommand for TabSwitch {}
impl std::fmt::Display for TabSwitch {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{} {}", Self::command(), self.movement)
}
}
impl LllRunnable for TabSwitch {
fn execute(&self, context: &mut LllContext, view: &LllView) -> Result<(), LllError> {
let mut new_index = context.curr_tab_index as i32 + self.movement;
let tab_len = context.tabs.len() as i32;
while new_index < 0 {
new_index += tab_len;
}
while new_index >= tab_len {
new_index -= tab_len;
}
let new_index = new_index as usize;
match Self::tab_switch(new_index, context, view) {
Ok(_) => Ok(()),
Err(e) => Err(LllError::IO(e)),
}
}
}
|
fn main() {
windows::core::build! {
Component::Enums::*,
};
}
|
use xshell::{cmd, Shell};
#[test]
fn versions_match() {
let sh = Shell::new().unwrap();
let read_version = |path: &str| {
let text = sh.read_file(path).unwrap();
let vers = text.lines().find(|it| it.starts_with("version =")).unwrap();
let vers = vers.splitn(2, '#').next().unwrap();
vers.trim_start_matches("version =").trim().trim_matches('"').to_string()
};
let v1 = read_version("./Cargo.toml");
let v2 = read_version("./xshell-macros/Cargo.toml");
assert_eq!(v1, v2);
let cargo_toml = sh.read_file("./Cargo.toml").unwrap();
let dep = format!("xshell-macros = {{ version = \"={}\",", v1);
assert!(cargo_toml.contains(&dep));
}
#[test]
fn formatting() {
let sh = Shell::new().unwrap();
cmd!(sh, "cargo fmt --all -- --check").run().unwrap()
}
#[test]
fn current_version_in_changelog() {
let sh = Shell::new().unwrap();
let _p = sh.push_dir(env!("CARGO_MANIFEST_DIR"));
let changelog = sh.read_file("CHANGELOG.md").unwrap();
let current_version_header = format!("## {}", env!("CARGO_PKG_VERSION"));
assert_eq!(changelog.lines().filter(|&line| line == current_version_header).count(), 1);
}
|
//! Payload values.
//!
//! Type Attr represents an attribute of a Payload.
use super::token::Token;
use super::range::Range;
use super::symbol;
use std::slice;
extern crate libc;
/// A payload object.
#[repr(C)]
pub struct Payload {
typ: Token,
len: u32,
range: (u32, u32),
}
impl Payload {
/// Adds `data` as a slice.
pub fn add_slice(&mut self, data: &'static [u8]) {
unsafe {
symbol::Payload_addSlice.unwrap()(self, (data.as_ptr(), data.len()));
}
}
/// Returns an `Iterator` for the slices.
pub fn slices(&self) -> Box<Iterator<Item = &'static [u8]>> {
unsafe {
let mut size: libc::size_t = 0;
let ptr = symbol::Payload_slices.unwrap()(self, &mut size);
let s = slice::from_raw_parts(ptr, size);
Box::new(s.iter().map(|elem| {
let (data, len) = *elem;
slice::from_raw_parts(data, len)
}))
}
}
/// Returns the range of `self`.
pub fn range(&self) -> Range {
Range {
start: self.range.0,
end: self.range.1,
}
}
/// Sets the range of `self`.
pub fn set_range(&mut self, range: &Range) {
self.range = (range.start, range.end)
}
/// Returns the type of `self`.
pub fn typ(&self) -> Token {
self.typ
}
/// Sets the type of `self`.
pub fn set_typ(&mut self, id: Token) {
self.typ = id
}
}
|
//! Contains the `GenParamsIn` type,for printing generic parameters.
use syn::{
token::{Colon, Comma, Const, Star},
GenericParam, Generics,
};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use crate::utils::NoTokens;
/// Used to print (with ToTokens) the generc parameter differently depending on where
/// it is being used/declared.
///
/// One can also add stuff to be printed after lifetime/type parameters.
#[derive(Debug, Copy, Clone)]
pub struct GenParamsIn<'a, AL = NoTokens> {
pub generics: &'a Generics,
/// Where the generic parameters are being printed.
pub in_what: InWhat,
/// Whether type parameters are all `?Sized`
pub unsized_types: bool,
/// Whether type bounds will be printed in type parameter declarations.
pub with_bounds: bool,
skip_lifetimes: bool,
/// What will be printed after lifetime parameters
after_lifetimes: Option<AL>,
/// What will be printed after type parameters
after_types: Option<AL>,
skip_consts: bool,
skip_unbounded: bool,
}
/// Where the generic parameters are being printed.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum InWhat {
/// For the header of an impl block,as in the contents of `impl< ... >`.
ImplHeader,
/// For trait/struct/enum/union
ItemDecl,
/// For when using a generic as an argument for a trait/struct/enum/union.
ItemUse,
/// For defining the fields of a Dummy struct that is never instantiated,
/// only using its associated items.
DummyStruct,
}
impl<'a> GenParamsIn<'a> {
#[allow(dead_code)]
pub fn new(generics: &'a Generics, in_what: InWhat) -> Self {
Self {
generics,
in_what,
unsized_types: false,
with_bounds: true,
skip_lifetimes: false,
after_lifetimes: None,
after_types: None,
skip_consts: false,
skip_unbounded: false,
}
}
}
impl<'a, AL> GenParamsIn<'a, AL> {
/// Constructs a GenParamsIn that prints `after lifetimes` after lifetime parameters.
pub fn with_after_lifetimes(
generics: &'a Generics,
in_what: InWhat,
after_lifetimes: AL,
) -> Self {
Self {
generics,
in_what,
unsized_types: false,
with_bounds: true,
skip_lifetimes: false,
after_lifetimes: Some(after_lifetimes),
after_types: None,
skip_consts: false,
skip_unbounded: false,
}
}
/// Constructs a GenParamsIn that prints `after types` after type parameters.
pub fn with_after_types(generics: &'a Generics, in_what: InWhat, after_types: AL) -> Self {
Self {
generics,
in_what,
unsized_types: false,
with_bounds: true,
skip_lifetimes: false,
after_lifetimes: None,
after_types: Some(after_types),
skip_consts: false,
skip_unbounded: false,
}
}
/// Removes the bounds on type parameters on type parameter declarations.
pub fn set_no_bounds(&mut self) {
self.with_bounds = false;
}
/// Makes all type parameters `?Sized`.
#[allow(dead_code)]
pub fn set_unsized_types(&mut self) {
self.unsized_types = true;
}
pub fn skip_lifetimes(&mut self) {
self.skip_lifetimes = true;
}
pub fn skip_consts(&mut self) {
self.skip_consts = true;
}
pub fn skip_unbounded(&mut self) {
self.skip_unbounded = true;
self.skip_consts();
self.skip_lifetimes();
}
pub fn skips_unbounded(&self) -> bool {
self.skip_unbounded
}
/// Queries whether bounds are printed.
pub fn outputs_bounds(&self) -> bool {
self.with_bounds && matches!(self.in_what, InWhat::ImplHeader | InWhat::ItemDecl)
}
/// Queries whether all types have a `?Sized` bound.
pub fn are_types_unsized(&self) -> bool {
self.unsized_types && matches!(self.in_what, InWhat::ItemDecl | InWhat::ImplHeader)
}
}
impl<'a, AL> ToTokens for GenParamsIn<'a, AL>
where
AL: ToTokens,
{
fn to_tokens(&self, ts: &mut TokenStream) {
let with_bounds = self.outputs_bounds();
let with_default = self.in_what == InWhat::ItemDecl;
let in_dummy_struct = self.in_what == InWhat::DummyStruct;
let unsized_types = self.are_types_unsized();
let mut iter = self.generics.params.iter().peekable();
let comma = Comma::default();
let brace = syn::token::Brace::default();
if self.skip_lifetimes {
while let Some(GenericParam::Lifetime { .. }) = iter.peek() {
iter.next();
}
} else {
while let Some(GenericParam::Lifetime(gen)) = iter.peek() {
iter.next();
if in_dummy_struct {
syn::token::And::default().to_tokens(ts);
gen.lifetime.to_tokens(ts);
syn::token::Paren::default().surround(ts, |_| ());
} else {
gen.lifetime.to_tokens(ts);
if with_bounds {
gen.colon_token.to_tokens(ts);
gen.bounds.to_tokens(ts);
}
}
comma.to_tokens(ts);
}
}
self.after_lifetimes.to_tokens(ts);
while let Some(GenericParam::Type(gen)) = iter.peek() {
iter.next();
if gen.bounds.is_empty() && self.skip_unbounded {
continue;
}
if in_dummy_struct {
Star::default().to_tokens(ts);
Const::default().to_tokens(ts);
}
gen.ident.to_tokens(ts);
if (with_bounds && gen.colon_token.is_some()) || unsized_types {
Colon::default().to_tokens(ts);
if unsized_types {
quote!(?Sized+).to_tokens(ts);
}
if with_bounds {
gen.bounds.to_tokens(ts);
}
}
if with_default {
gen.eq_token.to_tokens(ts);
gen.default.to_tokens(ts);
}
comma.to_tokens(ts);
}
self.after_types.to_tokens(ts);
if !in_dummy_struct && !self.skip_consts {
while let Some(GenericParam::Const(gen)) = iter.peek() {
iter.next();
if self.in_what != InWhat::ItemUse {
gen.const_token.to_tokens(ts);
}
if self.in_what == InWhat::ItemUse {
// Have to surround the const parameter when it's used,
// because otherwise it's interpreted as a type parameter.
// Remove this branch once outputting the identifier
// for the const parameter just works.
brace.surround(ts, |ts| {
gen.ident.to_tokens(ts);
});
} else {
gen.ident.to_tokens(ts);
}
if self.in_what != InWhat::ItemUse {
Colon::default().to_tokens(ts);
gen.ty.to_tokens(ts);
}
if with_default {
gen.eq_token.to_tokens(ts);
gen.default.to_tokens(ts);
}
comma.to_tokens(ts);
}
}
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use common_base::base::tokio;
use common_base::base::tokio::sync::Mutex as TokioMutex;
use common_base::base::tokio::sync::RwLock;
use common_base::runtime::GlobalQueryRuntime;
use common_base::runtime::TrySpawn;
use common_catalog::table_context::StageAttachment;
use common_exception::ErrorCode;
use common_exception::Result;
use serde::Deserialize;
use serde::Serialize;
use super::HttpQueryContext;
use crate::interpreters::InterpreterQueryLog;
use crate::servers::http::v1::query::execute_state::ExecuteStarting;
use crate::servers::http::v1::query::execute_state::ExecuteStopped;
use crate::servers::http::v1::query::execute_state::Progresses;
use crate::servers::http::v1::query::expirable::Expirable;
use crate::servers::http::v1::query::expirable::ExpiringState;
use crate::servers::http::v1::query::http_query_manager::HttpQueryConfig;
use crate::servers::http::v1::query::sized_spsc::sized_spsc;
use crate::servers::http::v1::query::ExecuteState;
use crate::servers::http::v1::query::ExecuteStateKind;
use crate::servers::http::v1::query::Executor;
use crate::servers::http::v1::query::PageManager;
use crate::servers::http::v1::query::ResponseData;
use crate::servers::http::v1::query::Wait;
use crate::servers::http::v1::HttpQueryManager;
use crate::sessions::QueryAffect;
use crate::sessions::SessionType;
use crate::sessions::TableContext;
fn default_as_true() -> bool {
true
}
#[derive(Deserialize, Debug)]
pub struct HttpQueryRequest {
pub session_id: Option<String>,
pub session: Option<HttpSessionConf>,
pub sql: String,
#[serde(default)]
pub pagination: PaginationConf,
#[serde(default = "default_as_true")]
pub string_fields: bool,
pub stage_attachment: Option<StageAttachmentConf>,
}
const DEFAULT_MAX_ROWS_IN_BUFFER: usize = 5 * 1000 * 1000;
const DEFAULT_MAX_ROWS_PER_PAGE: usize = 10000;
const DEFAULT_WAIT_TIME_SECS: u32 = 1;
fn default_max_rows_in_buffer() -> usize {
DEFAULT_MAX_ROWS_IN_BUFFER
}
fn default_max_rows_per_page() -> usize {
DEFAULT_MAX_ROWS_PER_PAGE
}
fn default_wait_time_secs() -> u32 {
DEFAULT_WAIT_TIME_SECS
}
#[derive(Deserialize, Debug)]
pub struct PaginationConf {
#[serde(default = "default_wait_time_secs")]
pub(crate) wait_time_secs: u32,
#[serde(default = "default_max_rows_in_buffer")]
pub(crate) max_rows_in_buffer: usize,
#[serde(default = "default_max_rows_per_page")]
pub(crate) max_rows_per_page: usize,
}
impl Default for PaginationConf {
fn default() -> Self {
PaginationConf {
wait_time_secs: 1,
max_rows_in_buffer: DEFAULT_MAX_ROWS_IN_BUFFER,
max_rows_per_page: DEFAULT_MAX_ROWS_PER_PAGE,
}
}
}
impl PaginationConf {
pub(crate) fn get_wait_type(&self) -> Wait {
let t = self.wait_time_secs;
if t > 0 {
Wait::Deadline(Instant::now() + Duration::from_secs(t as u64))
} else {
Wait::Async
}
}
}
#[derive(Deserialize, Serialize, Debug, Default, PartialEq, Eq, Clone)]
pub struct HttpSessionConf {
#[serde(skip_serializing_if = "Option::is_none")]
pub database: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub keep_server_session_secs: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub settings: Option<BTreeMap<String, String>>,
}
impl HttpSessionConf {
fn apply_affect(&self, affect: &QueryAffect) -> HttpSessionConf {
let mut ret = self.clone();
match affect {
QueryAffect::UseDB { name } => {
ret.database = Some(name.to_string());
}
QueryAffect::ChangeSettings {
keys,
values,
is_globals: _,
} => {
let settings = ret.settings.get_or_insert_default();
for (key, value) in keys.iter().zip(values) {
settings.insert(key.to_string(), value.to_string());
}
}
_ => {}
}
ret
}
}
#[derive(Deserialize, Debug, Clone)]
pub struct StageAttachmentConf {
/// location of the stage
/// for example: @stage_name/path/to/file, @~/path/to/file
pub(crate) location: String,
pub(crate) file_format_options: Option<BTreeMap<String, String>>,
pub(crate) copy_options: Option<BTreeMap<String, String>>,
}
#[derive(Debug, Clone)]
pub struct ResponseState {
pub running_time_ms: f64,
pub progresses: Progresses,
pub state: ExecuteStateKind,
pub affect: Option<QueryAffect>,
pub error: Option<ErrorCode>,
}
pub struct HttpQueryResponseInternal {
pub data: Option<ResponseData>,
pub session_id: String,
pub session: Option<HttpSessionConf>,
pub state: ResponseState,
}
pub enum ExpireState {
Working,
ExpireAt(Instant),
Removed,
}
pub enum ExpireResult {
Expired,
Sleep(Duration),
Removed,
}
pub struct HttpQuery {
pub(crate) id: String,
pub(crate) session_id: String,
request: HttpQueryRequest,
state: Arc<RwLock<Executor>>,
page_manager: Arc<TokioMutex<PageManager>>,
config: HttpQueryConfig,
expire_state: Arc<TokioMutex<ExpireState>>,
}
impl HttpQuery {
pub(crate) async fn try_create(
ctx: &HttpQueryContext,
request: HttpQueryRequest,
config: HttpQueryConfig,
) -> Result<Arc<HttpQuery>> {
let http_query_manager = HttpQueryManager::instance();
let session = if let Some(id) = &request.session_id {
let session = http_query_manager.get_session(id).await.ok_or_else(|| {
ErrorCode::UnknownSession(format!("unknown session-id {}, maybe expired", id))
})?;
let mut n = 1;
while let ExpiringState::InUse(query_id) = session.expire_state() {
if let Some(last_query) = &http_query_manager.get_query(&query_id).await {
if last_query.get_state().await.state == ExecuteStateKind::Running {
return Err(ErrorCode::BadArguments(
"last query on the session not finished",
));
} else {
http_query_manager.remove_query(&query_id).await;
}
}
// wait for Arc<QueryContextShared> to drop and detach itself from session
// should not take too long
tokio::time::sleep(Duration::from_millis(1)).await;
n += 1;
if n > 10 {
return Err(ErrorCode::Internal("last query stop but not released"));
}
}
session
} else {
ctx.get_session(SessionType::HTTPQuery)
};
if let Some(session_conf) = &request.session {
if let Some(db) = &session_conf.database {
session.set_current_database(db.clone());
}
if let Some(conf_settings) = &session_conf.settings {
let settings = session.get_settings();
for (k, v) in conf_settings {
settings.set_settings(k.to_string(), v.to_string(), false)?;
}
}
if let Some(secs) = session_conf.keep_server_session_secs {
if secs > 0 && request.session_id.is_none() {
http_query_manager
.add_session(session.clone(), Duration::from_secs(secs))
.await;
}
}
};
let session_id = session.get_id().clone();
let ctx = session.create_query_context().await?;
let id = ctx.get_id();
let sql = &request.sql;
tracing::info!("run query_id={id} in session_id={session_id}, sql='{sql}'");
match &request.stage_attachment {
Some(attachment) => ctx.attach_stage(StageAttachment {
location: attachment.location.clone(),
file_format_options: attachment.file_format_options.clone(),
copy_options: attachment.copy_options.clone(),
values_str: "".to_string(),
}),
None => {}
};
let (block_sender, block_receiver) = sized_spsc(request.pagination.max_rows_in_buffer);
let start_time = Instant::now();
let state = Arc::new(RwLock::new(Executor {
query_id: id.clone(),
start_time,
state: ExecuteState::Starting(ExecuteStarting { ctx: ctx.clone() }),
}));
let block_sender_closer = block_sender.closer();
let state_clone = state.clone();
let ctx_clone = ctx.clone();
let ctx_clone2 = ctx.clone();
let sql = request.sql.clone();
let query_id = id.clone();
let query_id_clone = id.clone();
let schema = ExecuteState::get_schema(&sql, ctx.clone()).await?;
let http_query_runtime_instance = GlobalQueryRuntime::instance();
http_query_runtime_instance
.runtime()
.try_spawn(async move {
let state = state_clone.clone();
if let Err(e) = ExecuteState::try_start_query(
state,
&sql,
session,
ctx_clone.clone(),
block_sender,
)
.await
{
InterpreterQueryLog::fail_to_start(ctx_clone.clone(), e.clone());
let state = ExecuteStopped {
stats: Progresses::default(),
reason: Err(e.clone()),
stop_time: Instant::now(),
affect: ctx_clone.get_affect(),
};
tracing::info!(
"http query {}, change state to Stopped, fail to start {:?}",
&query_id,
e
);
Executor::start_to_stop(&state_clone, ExecuteState::Stopped(Box::new(state)))
.await;
block_sender_closer.close();
}
})?;
let format_settings = ctx.get_format_settings()?;
let data = Arc::new(TokioMutex::new(PageManager::new(
query_id_clone,
request.pagination.max_rows_per_page,
block_receiver,
schema,
format_settings,
ctx_clone2,
)));
let query = HttpQuery {
id,
session_id,
request,
state,
page_manager: data,
config,
expire_state: Arc::new(TokioMutex::new(ExpireState::Working)),
};
Ok(Arc::new(query))
}
pub async fn get_response_page(&self, page_no: usize) -> Result<HttpQueryResponseInternal> {
let data = Some(self.get_page(page_no).await?);
let state = self.get_state().await;
let session_conf = self.request.session.clone().unwrap_or_default();
let session_conf = if let Some(affect) = &state.affect {
Some(session_conf.apply_affect(affect))
} else {
Some(session_conf)
};
Ok(HttpQueryResponseInternal {
data,
state,
session: session_conf,
session_id: self.session_id.clone(),
})
}
pub async fn get_response_state_only(&self) -> HttpQueryResponseInternal {
HttpQueryResponseInternal {
data: None,
session_id: self.session_id.clone(),
state: self.get_state().await,
session: None,
}
}
async fn get_state(&self) -> ResponseState {
let state = self.state.read().await;
let (exe_state, err) = state.state.extract();
ResponseState {
running_time_ms: state.elapsed().as_secs_f64() * 1000.0,
progresses: state.get_progress(),
state: exe_state,
error: err,
affect: state.get_affect(),
}
}
async fn get_page(&self, page_no: usize) -> Result<ResponseData> {
let mut page_manager = self.page_manager.lock().await;
let page = page_manager
.get_a_page(page_no, &self.request.pagination.get_wait_type())
.await?;
let response = ResponseData {
page,
next_page_no: page_manager.next_page_no(),
};
Ok(response)
}
pub async fn kill(&self) {
Executor::stop(
&self.state,
Err(ErrorCode::AbortedQuery("killed by http")),
true,
)
.await;
}
pub async fn detach(&self) {
let data = self.page_manager.lock().await;
data.detach().await
}
pub async fn update_expire_time(&self, before_wait: bool) {
let duration = Duration::from_secs(self.config.result_timeout_secs)
+ if before_wait {
Duration::from_secs(self.request.pagination.wait_time_secs as u64)
} else {
Duration::new(0, 0)
};
let deadline = Instant::now() + duration;
let mut t = self.expire_state.lock().await;
*t = ExpireState::ExpireAt(deadline);
}
pub async fn mark_removed(&self) {
let mut t = self.expire_state.lock().await;
*t = ExpireState::Removed;
}
// return Duration to sleep
pub async fn check_expire(&self) -> ExpireResult {
let expire_state = self.expire_state.lock().await;
match *expire_state {
ExpireState::ExpireAt(expire_at) => {
let now = Instant::now();
if now >= expire_at {
ExpireResult::Expired
} else {
ExpireResult::Sleep(expire_at - now)
}
}
ExpireState::Removed => ExpireResult::Removed,
ExpireState::Working => {
ExpireResult::Sleep(Duration::from_secs(self.config.result_timeout_secs))
}
}
}
}
|
use crate::context::RpcContext;
use crate::v02::types::reply::Transaction;
use anyhow::Context;
use pathfinder_common::{BlockId, TransactionIndex};
use starknet_gateway_types::reply::transaction::Transaction as GatewayTransaction;
#[derive(serde::Deserialize, Debug, PartialEq, Eq)]
pub struct GetTransactionByBlockIdAndIndexInput {
block_id: BlockId,
index: TransactionIndex,
}
crate::error::generate_rpc_error_subset!(
GetTransactionByBlockIdAndIndexError: BlockNotFound,
InvalidTxnIndex
);
pub async fn get_transaction_by_block_id_and_index_impl(
context: RpcContext,
input: GetTransactionByBlockIdAndIndexInput,
) -> Result<GatewayTransaction, GetTransactionByBlockIdAndIndexError> {
let index: usize = input
.index
.get()
.try_into()
.map_err(|_| GetTransactionByBlockIdAndIndexError::InvalidTxnIndex)?;
let block_id = match input.block_id {
BlockId::Pending => {
return get_transaction_from_pending(&context.pending_data, index).await
}
other => other.try_into().expect("Only pending cast should fail"),
};
let storage = context.storage.clone();
let span = tracing::Span::current();
let jh = tokio::task::spawn_blocking(move || {
let _g = span.enter();
let mut db = storage
.connection()
.context("Opening database connection")?;
let db_tx = db.transaction().context("Creating database transaction")?;
// Get the transaction from storage.
match db_tx
.transaction_at_block(block_id, index)
.context("Reading transaction from database")?
{
Some(transaction) => Ok(transaction),
None => {
// We now need to check whether it was the block hash or transaction index which were invalid. We do this by checking if the block exists
// at all. If no, then the block hash is invalid. If yes, then the index is invalid.
let block_exists = db_tx
.block_exists(block_id)
.context("Querying block existence")?;
if block_exists {
Err(GetTransactionByBlockIdAndIndexError::InvalidTxnIndex)
} else {
Err(GetTransactionByBlockIdAndIndexError::BlockNotFound)
}
}
}
});
jh.await.context("Database read panic or shutting down")?
}
pub async fn get_transaction_by_block_id_and_index(
context: RpcContext,
input: GetTransactionByBlockIdAndIndexInput,
) -> Result<Transaction, GetTransactionByBlockIdAndIndexError> {
get_transaction_by_block_id_and_index_impl(context, input)
.await
.map(Into::into)
}
async fn get_transaction_from_pending(
pending: &Option<starknet_gateway_types::pending::PendingData>,
index: usize,
) -> Result<GatewayTransaction, GetTransactionByBlockIdAndIndexError> {
// We return InvalidTxnIndex even if the pending block is technically missing.
// The absence of the pending block should be transparent to the end-user so
// we effectively handle it as an empty pending block.
match pending {
Some(pending) => pending.block().await.map_or_else(
|| Err(GetTransactionByBlockIdAndIndexError::InvalidTxnIndex),
|block| {
block.transactions.get(index).map_or(
Err(GetTransactionByBlockIdAndIndexError::InvalidTxnIndex),
|txn| Ok(txn.clone()),
)
},
),
None => Err(GetTransactionByBlockIdAndIndexError::InvalidTxnIndex),
}
}
#[cfg(test)]
mod tests {
use super::*;
use pathfinder_common::macro_prelude::*;
use pathfinder_common::{BlockHash, BlockNumber};
use stark_hash::Felt;
mod parsing {
use super::*;
use jsonrpsee::types::Params;
#[test]
fn positional_args() {
let positional = r#"[
{"block_hash": "0xdeadbeef"},
1
]"#;
let positional = Params::new(Some(positional));
let input = positional
.parse::<GetTransactionByBlockIdAndIndexInput>()
.unwrap();
assert_eq!(
input,
GetTransactionByBlockIdAndIndexInput {
block_id: BlockId::Hash(block_hash!("0xdeadbeef")),
index: TransactionIndex::new_or_panic(1),
}
)
}
#[test]
fn named_args() {
let named_args = r#"{
"block_id": {"block_hash": "0xdeadbeef"},
"index": 1
}"#;
let named_args = Params::new(Some(named_args));
let input = named_args
.parse::<GetTransactionByBlockIdAndIndexInput>()
.unwrap();
assert_eq!(
input,
GetTransactionByBlockIdAndIndexInput {
block_id: BlockId::Hash(block_hash!("0xdeadbeef")),
index: TransactionIndex::new_or_panic(1),
}
)
}
}
mod errors {
use super::*;
#[tokio::test]
async fn block_not_found() {
let context = RpcContext::for_tests();
let input = GetTransactionByBlockIdAndIndexInput {
block_id: BlockId::Hash(BlockHash(Felt::ZERO)),
index: TransactionIndex::new_or_panic(0),
};
let result = get_transaction_by_block_id_and_index(context, input).await;
assert_matches::assert_matches!(
result,
Err(GetTransactionByBlockIdAndIndexError::BlockNotFound)
);
}
#[tokio::test]
async fn invalid_index() {
let context = RpcContext::for_tests();
let input = GetTransactionByBlockIdAndIndexInput {
block_id: BlockId::Hash(block_hash_bytes!(b"genesis")),
index: TransactionIndex::new_or_panic(123),
};
let result = get_transaction_by_block_id_and_index(context, input).await;
assert_matches::assert_matches!(
result,
Err(GetTransactionByBlockIdAndIndexError::InvalidTxnIndex)
);
}
}
#[tokio::test]
async fn by_block_number() {
let context = RpcContext::for_tests();
let input = GetTransactionByBlockIdAndIndexInput {
block_id: BlockId::Number(BlockNumber::new_or_panic(0)),
index: TransactionIndex::new_or_panic(0),
};
let result = get_transaction_by_block_id_and_index(context, input)
.await
.unwrap();
assert_eq!(result.hash(), transaction_hash_bytes!(b"txn 0"));
}
#[tokio::test]
async fn by_block_hash() {
let context = RpcContext::for_tests();
let input = GetTransactionByBlockIdAndIndexInput {
block_id: BlockId::Hash(block_hash_bytes!(b"genesis")),
index: TransactionIndex::new_or_panic(0),
};
let result = get_transaction_by_block_id_and_index(context, input)
.await
.unwrap();
assert_eq!(result.hash(), transaction_hash_bytes!(b"txn 0"));
}
#[tokio::test]
async fn by_latest() {
let context = RpcContext::for_tests();
let input = GetTransactionByBlockIdAndIndexInput {
block_id: BlockId::Latest,
index: TransactionIndex::new_or_panic(0),
};
let result = get_transaction_by_block_id_and_index(context, input)
.await
.unwrap();
assert_eq!(result.hash(), transaction_hash_bytes!(b"txn 3"));
}
#[tokio::test]
async fn by_pending() {
let context = RpcContext::for_tests_with_pending().await;
const TX_IDX: usize = 1;
let expected = context
.pending_data
.as_ref()
.unwrap()
.block()
.await
.unwrap();
assert!(TX_IDX <= expected.transactions.len());
let expected: Transaction = expected.transactions.get(TX_IDX).unwrap().into();
let input = GetTransactionByBlockIdAndIndexInput {
block_id: BlockId::Pending,
index: TransactionIndex::new_or_panic(TX_IDX.try_into().unwrap()),
};
let result = get_transaction_by_block_id_and_index(context, input)
.await
.unwrap();
assert_eq!(result, expected);
}
}
|
use geoip2_city::CityApiResponse;
use std::fmt;
use std::fmt::{Display, Formatter};
/// A unique identifier for a datacenter. It consists of a AS Number, ISO-3166 country code, and
/// optionally a city name.
#[derive(Clone, Debug, Hash, Ord, PartialOrd, Eq, PartialEq)]
pub struct DatacenterIdentifier {
autonomous_system_number: u32,
country_code: String,
city_name: Option<String>,
}
impl From<CityApiResponse> for DatacenterIdentifier {
fn from(val: CityApiResponse) -> Self {
Self {
autonomous_system_number: val.traits.autonomous_system_number,
country_code: val
.country
.map(|c| c.iso_code)
.unwrap_or_else(|| "XX".to_string()),
city_name: val.city.and_then(|c| c.names.get("en").cloned()),
}
}
}
impl Display for DatacenterIdentifier {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match &self.city_name {
Some(cn) => {
write!(
f,
"{}-{}-{}",
self.autonomous_system_number, self.country_code, cn
)
}
None => {
write!(f, "{}-{}", self.autonomous_system_number, self.country_code)
}
}
}
}
|
mod tmp_type_element;
mod type_element;
|
use crate::instruction::Instruction;
use crate::register::Register;
pub struct Stack {
pub i: u16,
pub counter: u16,
pub registers: Register,
pub call_stack: Vec<u16>,
pub memory: Vec<u8>,
}
impl Stack {
pub fn get_next_instruction(&mut self) -> Option<Instruction> {
if (self.counter + 2) as usize >= self.memory.len() {
return None
}
let x = &self.memory[self.counter as usize..(self.counter + 2) as usize];
let bit = ((x[0] as u16) << 8) | x[1] as u16;
/*if bit == 0x00000000 {
return None
}*/
self.counter += 2;
return Some(Instruction::new(bit))
}
} |
use byteorder::{WriteBytesExt, BigEndian};
use std::io::{BufWriter, Write, Cursor};
use std::net::TcpStream;
use {Packet, QoS, Error, Result, MAX_PAYLOAD_SIZE, SubscribeTopic, SubscribeReturnCodes};
pub trait MqttWrite: WriteBytesExt {
fn write_packet(&mut self, packet: &Packet) -> Result<()> {
match packet {
&Packet::Connect(ref connect) => {
try!(self.write_u8(0b00010000));
let prot_name = connect.protocol.name();
let mut len = 8 + prot_name.len() + connect.client_id.len();
if let Some(ref last_will) = connect.last_will {
len += 4 + last_will.topic.len() + last_will.message.len();
}
if let Some(ref username) = connect.username {
len += 2 + username.len();
}
if let Some(ref password) = connect.password {
len += 2 + password.len();
}
try!(self.write_remaining_length(len));
try!(self.write_mqtt_string(prot_name));
try!(self.write_u8(connect.protocol.level()));
let mut connect_flags = 0;
if connect.clean_session {
connect_flags |= 0x02;
}
if let Some(ref last_will) = connect.last_will {
connect_flags |= 0x04;
connect_flags |= last_will.qos.to_u8() << 3;
if last_will.retain {
connect_flags |= 0x20;
}
}
if let Some(_) = connect.password {
connect_flags |= 0x40;
}
if let Some(_) = connect.username {
connect_flags |= 0x80;
}
try!(self.write_u8(connect_flags));
try!(self.write_u16::<BigEndian>(connect.keep_alive));
try!(self.write_mqtt_string(connect.client_id.as_ref()));
if let Some(ref last_will) = connect.last_will {
try!(self.write_mqtt_string(last_will.topic.as_ref()));
try!(self.write_mqtt_string(last_will.message.as_ref()));
}
if let Some(ref username) = connect.username {
try!(self.write_mqtt_string(username));
}
if let Some(ref password) = connect.password {
try!(self.write_mqtt_string(password));
}
Ok(())
},
&Packet::Connack(ref connack) => {
try!(self.write(&[0x20, 0x02, connack.session_present as u8, connack.code.to_u8()]));
Ok(())
},
&Packet::Publish(ref publish) => {
try!(self.write_u8(0b00110000 | publish.retain as u8 | (publish.qos.to_u8() << 1) | ((publish.dup as u8) << 3)));
let mut len = publish.topic_name.len() + 2 + publish.payload.len();
if publish.qos != QoS::AtMostOnce && None != publish.pid {
len += 2;
}
try!(self.write_remaining_length(len));
try!(self.write_mqtt_string(publish.topic_name.as_str()));
if publish.qos != QoS::AtMostOnce {
if let Some(pid) = publish.pid {
try!(self.write_u16::<BigEndian>(pid.0));
}
}
try!(self.write(&publish.payload.as_ref()));
Ok(())
},
&Packet::Puback(ref pid) => {
try!(self.write(&[0x40, 0x02]));
try!(self.write_u16::<BigEndian>(pid.0));
Ok(())
},
&Packet::Pubrec(ref pid) => {
try!(self.write(&[0x50, 0x02]));
try!(self.write_u16::<BigEndian>(pid.0));
Ok(())
},
&Packet::Pubrel(ref pid) => {
try!(self.write(&[0x62, 0x02]));
try!(self.write_u16::<BigEndian>(pid.0));
Ok(())
},
&Packet::Pubcomp(ref pid) => {
try!(self.write(&[0x70, 0x02]));
try!(self.write_u16::<BigEndian>(pid.0));
Ok(())
},
&Packet::Subscribe(ref subscribe) => {
try!(self.write(&[0x82]));
let len = 2 + subscribe.topics.iter().fold(0, |s, ref t| s + t.topic_path.len() + 3);
try!(self.write_remaining_length(len));
try!(self.write_u16::<BigEndian>(subscribe.pid.0));
for topic in subscribe.topics.as_ref() as &Vec<SubscribeTopic> {
try!(self.write_mqtt_string(topic.topic_path.as_str()));
try!(self.write_u8(topic.qos.to_u8()));
}
Ok(())
},
&Packet::Suback(ref suback) => {
try!(self.write(&[0x90]));
try!(self.write_remaining_length(suback.return_codes.len() + 2));
try!(self.write_u16::<BigEndian>(suback.pid.0));
let payload: Vec<u8> = suback.return_codes.iter().map({ |&code|
match code {
SubscribeReturnCodes::Success(qos) => qos.to_u8(),
SubscribeReturnCodes::Failure => 0x80
}
}).collect();
try!(self.write(&payload));
Ok(())
},
&Packet::Unsubscribe(ref unsubscribe) => {
try!(self.write(&[0xA2]));
let len = 2 + unsubscribe.topics.iter().fold(0, |s, ref topic| s + topic.len() + 2);
try!(self.write_remaining_length(len));
try!(self.write_u16::<BigEndian>(unsubscribe.pid.0));
for topic in unsubscribe.topics.as_ref() as &Vec<String> {
try!(self.write_mqtt_string(topic.as_str()));
}
Ok(())
},
&Packet::Unsuback(ref pid) => {
try!(self.write(&[0xB0, 0x02]));
try!(self.write_u16::<BigEndian>(pid.0));
Ok(())
},
&Packet::Pingreq => {
try!(self.write(&[0xc0, 0]));
Ok(())
},
&Packet::Pingresp => {
try!(self.write(&[0xd0, 0]));
Ok(())
},
&Packet::Disconnect => {
try!(self.write(&[0xe0, 0]));
Ok(())
}
}
}
fn write_mqtt_string(&mut self, string: &str) -> Result<()> {
try!(self.write_u16::<BigEndian>(string.len() as u16));
try!(self.write(string.as_bytes()));
Ok(())
}
fn write_remaining_length(&mut self, len: usize) -> Result<()> {
if len > MAX_PAYLOAD_SIZE {
return Err(Error::PayloadTooLong);
}
let mut done = false;
let mut x = len;
while !done {
let mut byte = (x % 128) as u8;
x = x / 128;
if x > 0 {
byte = byte | 128;
}
try!(self.write_u8(byte));
done = x <= 0;
}
Ok(())
}
}
impl MqttWrite for TcpStream {}
impl MqttWrite for Cursor<Vec<u8>> {}
impl<T: Write> MqttWrite for BufWriter<T> {}
#[cfg(test)]
mod test {
use std::io::Cursor;
use std::sync::Arc;
use super::{MqttWrite};
use super::super::{Protocol, LastWill, QoS, PacketIdentifier, ConnectReturnCode, SubscribeTopic};
use super::super::mqtt::{
Packet,
Connect,
Connack,
Publish,
Subscribe
};
#[test]
fn write_packet_connect_mqtt_protocol_test() {
let connect = Packet::Connect(Box::new(Connect {
protocol: Protocol::MQTT(4),
keep_alive: 10,
client_id: "test".to_owned(),
clean_session: true,
last_will: Some(LastWill {
topic: "/a".to_owned(),
message: "offline".to_owned(),
retain: false,
qos: QoS::AtLeastOnce
}),
username: Some("rust".to_owned()),
password: Some("mq".to_owned())
}));
let mut stream = Cursor::new(Vec::new());
stream.write_packet(&connect).unwrap();
assert_eq!(stream.get_ref().clone(), vec![0x10, 39,
0x00, 0x04, 'M' as u8, 'Q' as u8, 'T' as u8, 'T' as u8,
0x04,
0b11001110, // +username, +password, -will retain, will qos=1, +last_will, +clean_session
0x00, 0x0a, // 10 sec
0x00, 0x04, 't' as u8, 'e' as u8, 's' as u8, 't' as u8, // client_id
0x00, 0x02, '/' as u8, 'a' as u8, // will topic = '/a'
0x00, 0x07, 'o' as u8, 'f' as u8, 'f' as u8, 'l' as u8, 'i' as u8, 'n' as u8, 'e' as u8, // will msg = 'offline'
0x00, 0x04, 'r' as u8, 'u' as u8, 's' as u8, 't' as u8, // username = 'rust'
0x00, 0x02, 'm' as u8, 'q' as u8 // password = 'mq'
]);
}
#[test]
fn write_packet_connect_mqisdp_protocol_test() {
let connect = Packet::Connect(Box::new(Connect {
protocol: Protocol::MQIsdp(3),
keep_alive: 60,
client_id: "test".to_owned(),
clean_session: false,
last_will: None,
username: None,
password: None
}));
let mut stream = Cursor::new(Vec::new());
stream.write_packet(&connect).unwrap();
assert_eq!(stream.get_ref().clone(), vec![0x10, 18,
0x00, 0x06, 'M' as u8, 'Q' as u8, 'I' as u8, 's' as u8, 'd' as u8, 'p' as u8,
0x03,
0b00000000, // -username, -password, -will retain, will qos=0, -last_will, -clean_session
0x00, 0x3c, // 60 sec
0x00, 0x04, 't' as u8, 'e' as u8, 's' as u8, 't' as u8 // client_id
]);
}
#[test]
fn write_packet_connack_test() {
let connack = Packet::Connack(Connack {
session_present: true,
code: ConnectReturnCode::Accepted
});
let mut stream = Cursor::new(Vec::new());
stream.write_packet(&connack).unwrap();
assert_eq!(stream.get_ref().clone(), vec![0b00100000, 0x02, 0x01, 0x00]);
}
#[test]
fn write_packet_publish_at_least_once_test() {
let publish = Packet::Publish(Box::new(Publish {
dup: false,
qos: QoS::AtLeastOnce,
retain: false,
topic_name: "a/b".to_owned(),
pid: Some(PacketIdentifier(10)),
payload: Arc::new(vec![0xF1, 0xF2, 0xF3, 0xF4])
}));
let mut stream = Cursor::new(Vec::new());
stream.write_packet(&publish).unwrap();
assert_eq!(stream.get_ref().clone(), vec![0b00110010, 11, 0x00, 0x03, 'a' as u8, '/' as u8, 'b' as u8, 0x00, 0x0a, 0xF1, 0xF2, 0xF3, 0xF4]);
}
#[test]
fn write_packet_publish_at_most_once_test() {
let publish = Packet::Publish(Box::new(Publish {
dup: false,
qos: QoS::AtMostOnce,
retain: false,
topic_name: "a/b".to_owned(),
pid: None,
payload: Arc::new(vec![0xE1, 0xE2, 0xE3, 0xE4])
}));
let mut stream = Cursor::new(Vec::new());
stream.write_packet(&publish).unwrap();
assert_eq!(stream.get_ref().clone(), vec![0b00110000, 9, 0x00, 0x03, 'a' as u8, '/' as u8, 'b' as u8, 0xE1, 0xE2, 0xE3, 0xE4]);
}
#[test]
fn write_packet_subscribe_test() {
let subscribe = Packet::Subscribe(Box::new(Subscribe {
pid: PacketIdentifier(260),
topics: vec![
SubscribeTopic { topic_path: "a/+".to_owned(), qos: QoS::AtMostOnce },
SubscribeTopic { topic_path: "#".to_owned(), qos: QoS::AtLeastOnce },
SubscribeTopic { topic_path: "a/b/c".to_owned(), qos: QoS::ExactlyOnce }
]
}));
let mut stream = Cursor::new(Vec::new());
stream.write_packet(&subscribe).unwrap();
assert_eq!(stream.get_ref().clone(),vec![0b10000010, 20,
0x01, 0x04, // pid = 260
0x00, 0x03, 'a' as u8, '/' as u8, '+' as u8, // topic filter = 'a/+'
0x00, // qos = 0
0x00, 0x01, '#' as u8, // topic filter = '#'
0x01, // qos = 1
0x00, 0x05, 'a' as u8, '/' as u8, 'b' as u8, '/' as u8, 'c' as u8, // topic filter = 'a/b/c'
0x02 // qos = 2
]);
}
}
|
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_operation_batch_delete_worlds(
input: &crate::input::BatchDeleteWorldsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_batch_delete_worlds_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_batch_describe_simulation_job(
input: &crate::input::BatchDescribeSimulationJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_batch_describe_simulation_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_cancel_deployment_job(
input: &crate::input::CancelDeploymentJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_cancel_deployment_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_cancel_simulation_job(
input: &crate::input::CancelSimulationJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_cancel_simulation_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_cancel_simulation_job_batch(
input: &crate::input::CancelSimulationJobBatchInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_cancel_simulation_job_batch_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_cancel_world_export_job(
input: &crate::input::CancelWorldExportJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_cancel_world_export_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_cancel_world_generation_job(
input: &crate::input::CancelWorldGenerationJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_cancel_world_generation_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_deployment_job(
input: &crate::input::CreateDeploymentJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_deployment_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_fleet(
input: &crate::input::CreateFleetInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_fleet_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_robot(
input: &crate::input::CreateRobotInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_robot_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_robot_application(
input: &crate::input::CreateRobotApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_robot_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_robot_application_version(
input: &crate::input::CreateRobotApplicationVersionInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_robot_application_version_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_simulation_application(
input: &crate::input::CreateSimulationApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_simulation_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_simulation_application_version(
input: &crate::input::CreateSimulationApplicationVersionInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_simulation_application_version_input(
&mut object,
input,
);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_simulation_job(
input: &crate::input::CreateSimulationJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_simulation_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_world_export_job(
input: &crate::input::CreateWorldExportJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_world_export_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_world_generation_job(
input: &crate::input::CreateWorldGenerationJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_world_generation_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_world_template(
input: &crate::input::CreateWorldTemplateInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_world_template_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_fleet(
input: &crate::input::DeleteFleetInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_fleet_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_robot(
input: &crate::input::DeleteRobotInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_robot_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_robot_application(
input: &crate::input::DeleteRobotApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_robot_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_simulation_application(
input: &crate::input::DeleteSimulationApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_simulation_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_world_template(
input: &crate::input::DeleteWorldTemplateInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_world_template_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_deregister_robot(
input: &crate::input::DeregisterRobotInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_deregister_robot_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_deployment_job(
input: &crate::input::DescribeDeploymentJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_deployment_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_fleet(
input: &crate::input::DescribeFleetInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_fleet_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_robot(
input: &crate::input::DescribeRobotInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_robot_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_robot_application(
input: &crate::input::DescribeRobotApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_robot_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_simulation_application(
input: &crate::input::DescribeSimulationApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_simulation_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_simulation_job(
input: &crate::input::DescribeSimulationJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_simulation_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_simulation_job_batch(
input: &crate::input::DescribeSimulationJobBatchInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_simulation_job_batch_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_world(
input: &crate::input::DescribeWorldInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_world_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_world_export_job(
input: &crate::input::DescribeWorldExportJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_world_export_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_world_generation_job(
input: &crate::input::DescribeWorldGenerationJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_world_generation_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_world_template(
input: &crate::input::DescribeWorldTemplateInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_world_template_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_get_world_template_body(
input: &crate::input::GetWorldTemplateBodyInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_get_world_template_body_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_deployment_jobs(
input: &crate::input::ListDeploymentJobsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_deployment_jobs_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_fleets(
input: &crate::input::ListFleetsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_fleets_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_robot_applications(
input: &crate::input::ListRobotApplicationsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_robot_applications_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_robots(
input: &crate::input::ListRobotsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_robots_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_simulation_applications(
input: &crate::input::ListSimulationApplicationsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_simulation_applications_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_simulation_job_batches(
input: &crate::input::ListSimulationJobBatchesInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_simulation_job_batches_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_simulation_jobs(
input: &crate::input::ListSimulationJobsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_simulation_jobs_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_world_export_jobs(
input: &crate::input::ListWorldExportJobsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_world_export_jobs_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_world_generation_jobs(
input: &crate::input::ListWorldGenerationJobsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_world_generation_jobs_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_worlds(
input: &crate::input::ListWorldsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_worlds_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_world_templates(
input: &crate::input::ListWorldTemplatesInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_world_templates_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_register_robot(
input: &crate::input::RegisterRobotInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_register_robot_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_restart_simulation_job(
input: &crate::input::RestartSimulationJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_restart_simulation_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_start_simulation_job_batch(
input: &crate::input::StartSimulationJobBatchInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_start_simulation_job_batch_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_sync_deployment_job(
input: &crate::input::SyncDeploymentJobInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_sync_deployment_job_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_tag_resource(
input: &crate::input::TagResourceInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_tag_resource_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_robot_application(
input: &crate::input::UpdateRobotApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_update_robot_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_simulation_application(
input: &crate::input::UpdateSimulationApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_update_simulation_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_world_template(
input: &crate::input::UpdateWorldTemplateInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_update_world_template_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
|
use f::FordFulkerson;
use procon_reader::ProconReader;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let h: usize = rd.get();
let w: usize = rd.get();
let n: usize = rd.get();
let mut g = FordFulkerson::new(h + n + n + w + 2);
let source = h + n + n + w;
let sink = source + 1;
for i in 0..h {
g.add_edge(source, i, 1);
}
for i in 0..n {
g.add_edge(h + i, h + n + i, 1);
}
for i in 0..w {
g.add_edge(h + n + n + i, sink, 1);
}
for i in 0..n {
let a: usize = rd.get();
let b: usize = rd.get();
let c: usize = rd.get();
let d: usize = rd.get();
for j in (a - 1)..c {
g.add_edge(j, h + i, 1);
}
for j in (b - 1)..d {
g.add_edge(h + n + i, h + n + n + j, 1);
}
}
let ans = g.max_flow(source, sink);
println!("{}", ans);
}
|
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkXcbSurfaceCreateInfoKHR {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub flags: VkXcbSurfaceCreateFlagBitsKHR,
pub connection: *const c_void,
pub window: u32,
}
impl VkXcbSurfaceCreateInfoKHR {
pub fn new<T, U>(flags: T, connection: &mut U, window: u32) -> Self
where
T: Into<VkXcbSurfaceCreateFlagBitsKHR>,
{
VkXcbSurfaceCreateInfoKHR {
sType: VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR,
pNext: ptr::null(),
flags: flags.into(),
connection: connection as *mut U as *mut c_void,
window: window,
}
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use lazy_static::lazy_static;
use alloc::collections::btree_map::BTreeMap;
use alloc::collections::btree_set::BTreeSet;
use alloc::string::String;
use alloc::string::ToString;
use alloc::vec::Vec;
use spin::Mutex;
use super::common::*;
use super::super::qlib::*;
lazy_static! {
static ref X86_FEATURES_FROM_STRING : Mutex<BTreeMap<String, i32>> = Mutex::new(BTreeMap::new());
static ref X86_FEATURE_STRINGS : BTreeMap<i32, &'static str> = [
// Block 0.
(X86Feature::X86FeatureSSE3 as i32, "pni"),
(X86Feature::X86FeaturePCLMULDQ as i32,"pclmulqdq"),
(X86Feature::X86FeatureDTES64 as i32, "dtes64"),
(X86Feature::X86FeatureMONITOR as i32, "monitor"),
(X86Feature::X86FeatureDSCPL as i32, "ds_cpl"),
(X86Feature::X86FeatureVMX as i32, "vmx"),
(X86Feature::X86FeatureSMX as i32, "smx"),
(X86Feature::X86FeatureEST as i32, "est"),
(X86Feature::X86FeatureTM2 as i32, "tm2"),
(X86Feature::X86FeatureSSSE3 as i32, "ssse3"),
(X86Feature::X86FeatureCNXTID as i32, "cid"),
(X86Feature::X86FeatureSDBG as i32, "sdbg"),
(X86Feature::X86FeatureFMA as i32, "fma"),
(X86Feature::X86FeatureCX16 as i32, "cx16"),
(X86Feature::X86FeatureXTPR as i32, "xtpr"),
(X86Feature::X86FeaturePDCM as i32, "pdcm"),
(X86Feature::X86FeaturePCID as i32, "pcid"),
(X86Feature::X86FeatureDCA as i32, "dca"),
(X86Feature::X86FeatureSSE4_1 as i32, "sse4_1"),
(X86Feature::X86FeatureSSE4_2 as i32, "sse4_2"),
(X86Feature::X86FeatureX2APIC as i32, "x2apic"),
(X86Feature::X86FeatureMOVBE as i32, "movbe"),
(X86Feature::X86FeaturePOPCNT as i32, "popcnt"),
(X86Feature::X86FeatureTSCD as i32, "tsc_deadline_timer"),
(X86Feature::X86FeatureAES as i32, "aes"),
(X86Feature::X86FeatureXSAVE as i32, "xsave"),
(X86Feature::X86FeatureAVX as i32, "avx"),
(X86Feature::X86FeatureF16C as i32, "f16c"),
(X86Feature::X86FeatureRDRAND as i32, "rdrand"),
// Block 1.
(X86Feature::X86FeatureFPU as i32, "fpu"),
(X86Feature::X86FeatureVME as i32, "vme"),
(X86Feature::X86FeatureDE as i32, "de"),
(X86Feature::X86FeaturePSE as i32, "pse"),
(X86Feature::X86FeatureTSC as i32, "tsc"),
(X86Feature::X86FeatureMSR as i32, "msr"),
(X86Feature::X86FeaturePAE as i32, "pae"),
(X86Feature::X86FeatureMCE as i32, "mce"),
(X86Feature::X86FeatureCX8 as i32, "cx8"),
(X86Feature::X86FeatureAPIC as i32, "apic"),
(X86Feature::X86FeatureSEP as i32, "sep"),
(X86Feature::X86FeatureMTRR as i32, "mtrr"),
(X86Feature::X86FeaturePGE as i32, "pge"),
(X86Feature::X86FeatureMCA as i32, "mca"),
(X86Feature::X86FeatureCMOV as i32, "cmov"),
(X86Feature::X86FeaturePAT as i32, "pat"),
(X86Feature::X86FeaturePSE36 as i32,"pse36"),
(X86Feature::X86FeaturePSN as i32, "pn"),
(X86Feature::X86FeatureCLFSH as i32,"clflush"),
(X86Feature::X86FeatureDS as i32, "dts"),
(X86Feature::X86FeatureACPI as i32, "acpi"),
(X86Feature::X86FeatureMMX as i32, "mmx"),
(X86Feature::X86FeatureFXSR as i32, "fxsr"),
(X86Feature::X86FeatureSSE as i32, "sse"),
(X86Feature::X86FeatureSSE2 as i32, "sse2"),
(X86Feature::X86FeatureSS as i32, "ss"),
(X86Feature::X86FeatureHTT as i32, "ht"),
(X86Feature::X86FeatureTM as i32, "tm"),
(X86Feature::X86FeatureIA64 as i32, "ia64"),
(X86Feature::X86FeaturePBE as i32, "pbe"),
// Block 2.
(X86Feature::X86FeatureFSGSBase as i32, "fsgsbase"),
(X86Feature::X86FeatureTSC_ADJUST as i32,"tsc_adjust"),
(X86Feature::X86FeatureBMI1 as i32, "bmi1"),
(X86Feature::X86FeatureHLE as i32, "hle"),
(X86Feature::X86FeatureAVX2 as i32, "avx2"),
(X86Feature::X86FeatureSMEP as i32, "smep"),
(X86Feature::X86FeatureBMI2 as i32, "bmi2"),
(X86Feature::X86FeatureERMS as i32, "erms"),
(X86Feature::X86FeatureINVPCID as i32, "invpcid"),
(X86Feature::X86FeatureRTM as i32, "rtm"),
(X86Feature::X86FeatureCQM as i32, "cqm"),
(X86Feature::X86FeatureMPX as i32, "mpx"),
(X86Feature::X86FeatureRDT as i32, "rdt_a"),
(X86Feature::X86FeatureAVX512F as i32, "avx512f"),
(X86Feature::X86FeatureAVX512DQ as i32, "avx512dq"),
(X86Feature::X86FeatureRDSEED as i32, "rdseed"),
(X86Feature::X86FeatureADX as i32, "adx"),
(X86Feature::X86FeatureSMAP as i32, "smap"),
(X86Feature::X86FeatureCLWB as i32, "clwb"),
(X86Feature::X86FeatureAVX512PF as i32, "avx512pf"),
(X86Feature::X86FeatureAVX512ER as i32, "avx512er"),
(X86Feature::X86FeatureAVX512CD as i32, "avx512cd"),
(X86Feature::X86FeatureSHA as i32, "sha_ni"),
(X86Feature::X86FeatureAVX512BW as i32, "avx512bw"),
(X86Feature::X86FeatureAVX512VL as i32, "avx512vl"),
// Block 3.
(X86Feature::X86FeatureAVX512VBMI as i32,"avx512vbmi"),
(X86Feature::X86FeatureUMIP as i32, "umip"),
(X86Feature::X86FeaturePKU as i32, "pku"),
// Block 4.
(X86Feature::X86FeatureXSAVEOPT as i32,"xsaveopt"),
(X86Feature::X86FeatureXSAVEC as i32, "xsavec"),
(X86Feature::X86FeatureXGETBV1 as i32, "xgetbv1"),
(X86Feature::X86FeatureXSAVES as i32, "xsaves"),
// Block 5.
(X86Feature::X86FeatureLAHF64 as i32, "lahf_lm"),// LAHF/SAHF in long mode
(X86Feature::X86FeatureCMP_LEGACY as i32, "cmp_legacy"),
(X86Feature::X86FeatureSVM as i32, "svm"),
(X86Feature::X86FeatureEXTAPIC as i32, "extapic"),
(X86Feature::X86FeatureCR8_LEGACY as i32, "cr8_legacy"),
(X86Feature::X86FeatureLZCNT as i32, "abm"),// Advanced bit manipulation
(X86Feature::X86FeatureSSE4A as i32, "sse4a"),
(X86Feature::X86FeatureMISALIGNSSE as i32, "misalignsse"),
(X86Feature::X86FeaturePREFETCHW as i32, "3dnowprefetch"),
(X86Feature::X86FeatureOSVW as i32, "osvw"),
(X86Feature::X86FeatureIBS as i32, "ibs"),
(X86Feature::X86FeatureXOP as i32, "xop"),
(X86Feature::X86FeatureSKINIT as i32, "skinit"),
(X86Feature::X86FeatureWDT as i32, "wdt"),
(X86Feature::X86FeatureLWP as i32, "lwp"),
(X86Feature::X86FeatureFMA4 as i32, "fma4"),
(X86Feature::X86FeatureTCE as i32, "tce"),
(X86Feature::X86FeatureTBM as i32, "tbm"),
(X86Feature::X86FeatureTOPOLOGY as i32, "topoext"),
(X86Feature::X86FeaturePERFCTR_CORE as i32,"perfctr_core"),
(X86Feature::X86FeaturePERFCTR_NB as i32, "perfctr_nb"),
(X86Feature::X86FeatureBPEXT as i32, "bpext"),
(X86Feature::X86FeaturePERFCTR_TSC as i32, "ptsc"),
(X86Feature::X86FeaturePERFCTR_LLC as i32, "perfctr_llc"),
(X86Feature::X86FeatureMWAITX as i32, "mwaitx"),
// Block 6.
(X86Feature::X86FeatureSYSCALL as i32, "syscall"),
(X86Feature::X86FeatureNX as i32, "nx"),
(X86Feature::X86FeatureMMXEXT as i32, "mmxext"),
(X86Feature::X86FeatureFXSR_OPT as i32,"fxsr_opt"),
(X86Feature::X86FeatureGBPAGES as i32, "pdpe1gb"),
(X86Feature::X86FeatureRDTSCP as i32, "rdtscp"),
(X86Feature::X86FeatureLM as i32, "lm"),
(X86Feature::X86Feature3DNOWEXT as i32,"3dnowext"),
(X86Feature::X86Feature3DNOW as i32, "3dnow"),
].iter().cloned().collect();
static ref X86_FEATURE_PARSE_ONLY_STRINGS : BTreeMap<i32, &'static str> = [
// Block 0.
(X86Feature::X86FeatureOSXSAVE as i32, "osxsave"),
// Block 2.
(X86Feature::X86FeatureFDP_EXCPTN_ONLY as i32, "fdp_excptn_only"),
(X86Feature::X86FeatureFPCSDS as i32, "fpcsds"),
(X86Feature::X86FeatureIPT as i32, "pt"),
(X86Feature::X86FeatureCLFLUSHOPT as i32, "clfushopt"),
// Block 3.
(X86Feature::X86FeaturePREFETCHWT1 as i32, "prefetchwt1"),
].iter().cloned().collect();
static ref CPU_FREQ_MHZ : Mutex<f64> = Mutex::new(0.0);
}
pub type Block = i32;
const BLOCK_SIZE: i32 = 32;
#[allow(non_camel_case_types)]
#[repr(i32)]
#[derive(Debug, Copy, Clone, PartialEq, Ord, Eq, PartialOrd)]
pub enum X86Feature {
// Block 0 constants are all of the "basic" feature bits returned by a cpuid in
// ecx with eax=1.
X86FeatureSSE3 = 0,
X86FeaturePCLMULDQ,
X86FeatureDTES64,
X86FeatureMONITOR,
X86FeatureDSCPL,
X86FeatureVMX,
X86FeatureSMX,
X86FeatureEST,
X86FeatureTM2,
X86FeatureSSSE3,
// Not a typo, "supplemental" SSE3.
X86FeatureCNXTID,
X86FeatureSDBG,
X86FeatureFMA,
X86FeatureCX16,
X86FeatureXTPR,
X86FeaturePDCM,
_Dummy1,
// ecx bit 16 is reserved.
X86FeaturePCID,
X86FeatureDCA,
X86FeatureSSE4_1,
X86FeatureSSE4_2,
X86FeatureX2APIC,
X86FeatureMOVBE,
X86FeaturePOPCNT,
X86FeatureTSCD,
X86FeatureAES,
X86FeatureXSAVE,
X86FeatureOSXSAVE,
X86FeatureAVX,
X86FeatureF16C,
X86FeatureRDRAND,
_Dummy2,
// ecx bit 31 is reserved.
// Block 1 constants are all of the "basic" feature bits returned by a cpuid in
// edx with eax=1.
X86FeatureFPU = 32,
X86FeatureVME,
X86FeatureDE,
X86FeaturePSE,
X86FeatureTSC,
X86FeatureMSR,
X86FeaturePAE,
X86FeatureMCE,
X86FeatureCX8,
X86FeatureAPIC,
_Dummy3,
// edx bit 10 is reserved.
X86FeatureSEP,
X86FeatureMTRR,
X86FeaturePGE,
X86FeatureMCA,
X86FeatureCMOV,
X86FeaturePAT,
X86FeaturePSE36,
X86FeaturePSN,
X86FeatureCLFSH,
_Dummy4,
// edx bit 20 is reserved.
X86FeatureDS,
X86FeatureACPI,
X86FeatureMMX,
X86FeatureFXSR,
X86FeatureSSE,
X86FeatureSSE2,
X86FeatureSS,
X86FeatureHTT,
X86FeatureTM,
X86FeatureIA64,
X86FeaturePBE,
// Block 2 bits are the "structured extended" features returned in ebx for
// eax=7, ecx=0.
X86FeatureFSGSBase = 2 * 32,
X86FeatureTSC_ADJUST,
_Dummy5,
// ebx bit 2 is reserved.
X86FeatureBMI1,
X86FeatureHLE,
X86FeatureAVX2,
X86FeatureFDP_EXCPTN_ONLY,
X86FeatureSMEP,
X86FeatureBMI2,
X86FeatureERMS,
X86FeatureINVPCID,
X86FeatureRTM,
X86FeatureCQM,
X86FeatureFPCSDS,
X86FeatureMPX,
X86FeatureRDT,
X86FeatureAVX512F,
X86FeatureAVX512DQ,
X86FeatureRDSEED,
X86FeatureADX,
X86FeatureSMAP,
X86FeatureAVX512IFMA,
X86FeaturePCOMMIT,
X86FeatureCLFLUSHOPT,
X86FeatureCLWB,
X86FeatureIPT,
// Intel processor trace.
X86FeatureAVX512PF,
X86FeatureAVX512ER,
X86FeatureAVX512CD,
X86FeatureSHA,
X86FeatureAVX512BW,
X86FeatureAVX512VL,
// Block 3 bits are the "extended" features returned in ecx for eax=7, ecx=0.
X86FeaturePREFETCHWT1 = 3 * 32,
X86FeatureAVX512VBMI,
X86FeatureUMIP,
X86FeaturePKU,
// Block 4 constants are for xsave capabilities in CPUID.(EAX=0DH,ECX=01H):EAX.
// The CPUID leaf is available only if 'X86FeatureXSAVE' is present.
X86FeatureXSAVEOPT = 4 * 32,
X86FeatureXSAVEC,
X86FeatureXGETBV1,
X86FeatureXSAVES,
// EAX[31:4] are reserved.
// Block 5 constants are the extended feature bits in
// CPUID.(EAX=0x80000001):ECX.
X86FeatureLAHF64 = 5 * 32,
X86FeatureCMP_LEGACY,
X86FeatureSVM,
X86FeatureEXTAPIC,
X86FeatureCR8_LEGACY,
X86FeatureLZCNT,
X86FeatureSSE4A,
X86FeatureMISALIGNSSE,
X86FeaturePREFETCHW,
X86FeatureOSVW,
X86FeatureIBS,
X86FeatureXOP,
X86FeatureSKINIT,
X86FeatureWDT,
_Dummy6,
// ecx bit 14 is reserved.
X86FeatureLWP,
X86FeatureFMA4,
X86FeatureTCE,
_Dummy7,
// ecx bit 18 is reserved.
_Dummy8,
// ecx bit 19 is reserved.
_Dummy9,
// ecx bit 20 is reserved.
X86FeatureTBM,
X86FeatureTOPOLOGY,
X86FeaturePERFCTR_CORE,
X86FeaturePERFCTR_NB,
_Dummy10,
// ecx bit 25 is reserved.
X86FeatureBPEXT,
X86FeaturePERFCTR_TSC,
X86FeaturePERFCTR_LLC,
X86FeatureMWAITX,
// ECX[31:30] are reserved.
// Block 6 constants are the extended feature bits in
// CPUID.(EAX=0x80000001):EDX.
//
// These are sparse, and so the bit positions are assigned manually.
Block6DuplicateMask = 0x183f3ff,
X86FeatureSYSCALL = 6 * 32 + 11,
X86FeatureNX = 6 * 32 + 20,
X86FeatureMMXEXT = 6 * 32 + 22,
X86FeatureFXSR_OPT = 6 * 32 + 25,
X86FeatureGBPAGES = 6 * 32 + 26,
X86FeatureRDTSCP = 6 * 32 + 27,
X86FeatureLM = 6 * 32 + 29,
X86Feature3DNOWEXT = 6 * 32 + 30,
X86Feature3DNOW = 6 * 32 + 31,
}
// linuxBlockOrder defines the order in which linux organizes the feature
// blocks. Linux also tracks feature bits in 32-bit blocks, but in an order
// which doesn't match well here, so for the /proc/cpuinfo generation we simply
// re-map the blocks to Linux's ordering and then go through the bits in each
// block.
const LINUX_BLOCK_ORDER: [Block; 7] = [1, 6, 0, 5, 2, 4, 3];
// The constants below are the lower or "standard" cpuid functions, ordered as
// defined by the hardware.
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Ord, Eq, PartialOrd)]
pub enum CpuidFunction {
vendorID = 0,
// Returns vendor ID and largest standard function.
featureInfo,
// Returns basic feature bits and processor signature.
intelCacheDescriptors,
// Returns list of cache descriptors. Intel only.
intelSerialNumber,
// Returns processor serial number (obsolete on new hardware). Intel only.
intelDeterministicCacheParams,
// Returns deterministic cache information. Intel only.
monitorMwaitParams,
// Returns information about monitor/mwait instructions.
powerParams,
// Returns information about power management and thermal sensors.
extendedFeatureInfo,
// Returns extended feature bits.
_dummy1,
// Function 0x8 is reserved.
intelDCAParams,
// Returns direct cache access information. Intel only.
intelPMCInfo,
// Returns information about performance monitoring features. Intel only.
intelX2APICInfo,
// Returns core/logical processor topology. Intel only.
_dummy12,
// Function 0xc is reserved.(/
xSaveInfo,
// Returns information about extended state management.
}
// The "extended" functions start at 0x80000000.
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Ord, Eq, PartialOrd)]
pub enum ExtendedFunction {
extendedFunctionInfo = 0x80000000,
// Returns highest available extended function in eax.
extendedFeatures,
// Returns some extended feature bits in edx and ecx.
}
// These are the extended floating point state features. They are used to
// enumerate floating point features in XCR0, XSTATE_BV, etc.
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Ord, Eq, PartialOrd)]
pub enum XSAVEFeature {
XSAVEFeatureX87 = 1 << 0,
XSAVEFeatureSSE = 1 << 1,
XSAVEFeatureAVX = 1 << 2,
XSAVEFeatureBNDREGS = 1 << 3,
XSAVEFeatureBNDCSR = 1 << 4,
XSAVEFeatureAVX512op = 1 << 5,
XSAVEFeatureAVX512zmm0 = 1 << 6,
XSAVEFeatureAVX512zmm16 = 1 << 7,
XSAVEFeaturePKRU = 1 << 9,
}
#[derive(Debug)]
pub struct Feature(pub i32);
impl Feature {
pub fn String(&self) -> String {
let s = self.flagString(false).to_string();
if s.as_str() != "" {
return s;
}
let block = self.0 / 32;
let bit = self.0 % 32;
return format!("<cpuflag {}; block {} bit {}>", self.0, block, bit)
}
fn flagString(&self, cpuinfoOnly: bool) -> &'static str {
match X86_FEATURE_STRINGS.get(&self.0) {
Some(s) => return *s,
None => {
if cpuinfoOnly {
match X86_FEATURE_PARSE_ONLY_STRINGS.get(&self.0) {
Some(s) => return *s,
None => return ""
}
}
return ""
}
}
}
}
fn featureID(b: Block, bit: i32) -> Feature {
return Feature(32 * b + bit)
}
#[derive(Debug, Default)]
pub struct FeatureSet {
// Set is the set of features that are enabled in this FeatureSet.
pub Set: BTreeSet<i32>,
// VendorID is the 12-char string returned in ebx:edx:ecx for eax=0.
pub VendorID: String,
// ExtendedFamily is part of the processor signature.
pub ExtendedFamily: u8,
// ExtendedModel is part of the processor signature.
pub ExtendedModel: u8,
// ProcessorType is part of the processor signature.
pub ProcessorType: u8,
// Family is part of the processor signature.
pub Family: u8,
// Model is part of the processor signature.
pub Model: u8,
// SteppingID is part of the processor signature.
pub SteppingID: u8,
}
impl FeatureSet {
pub fn FlagsString(&self, cpuinfoOnly: bool) -> String {
let mut s = Vec::new();
for b in &LINUX_BLOCK_ORDER {
for i in 0..BLOCK_SIZE as usize {
let f = featureID(*b, i as i32);
if self.Set.contains(&f.0) {
let fstr = f.flagString(cpuinfoOnly);
if fstr != "" {
s.push(fstr)
}
}
}
}
return s.join(" ")
}
pub fn CPUInfo(&self, cpu: u32) -> String {
let mut res = "".to_string();
let fs = self;
res += &format!("processor\t: {}\n", cpu);
res += &format!("vendor_id\t: {}\n", fs.VendorID);
res += &format!("cpu family\t: {}\n", ((fs.ExtendedFamily << 4) & 0xff) | fs.Family);
res += &format!("model\t\t: {}\n", ((fs.ExtendedModel << 4) & 0xff) | fs.Model);
res += &format!("model name\t: {}\n", "unknown");
res += &format!("stepping\t: {}\n", "unknown");
res += &format!("cpu MHz\t\t: {}\n", *CPU_FREQ_MHZ.lock());
res += &format!("fpu\t\t: yes\n");
res += &format!("fpu_exception\t: yes\n");
res += &format!("cpuid level\t: {}\n", CpuidFunction::xSaveInfo as u32);
res += &format!("wp\t\t: yes\n");
res += &format!("flags\t\t: {}\n", fs.FlagsString(true));
res += &format!("bogomips\t: {}\n", *CPU_FREQ_MHZ.lock());
res += &format!("clflush size\t: {}\n", 64);
res += &format!("cache_alignment\t: {}\n", 64);
res += &format!("address sizes\t: {} bits physical, {} bits virtual\n", 46, 48);
res += &format!("power management:");
res += &format!("");
return res;
}
pub fn AMD(&self) -> bool {
return self.VendorID.as_str() == "AuthenticAMD"
}
pub fn Intel(&self) -> bool {
return self.VendorID.as_str() == "GenuineIntel"
}
// blockMask returns the 32-bit mask associated with a block of features.
fn blockMask(&self, b: Block) -> u32 {
let mut mask: u32 = 0;
for i in 0..BLOCK_SIZE as usize {
if self.Set.contains(&featureID(b, i as i32).0) {
mask |= 1 << i;
}
}
return mask
}
// Remove removes a Feature from a FeatureSet. It ignores features
// that are not in the FeatureSet.
pub fn Remove(&mut self, feature: Feature) {
self.Set.remove(&feature.0);
}
// Add adds a Feature to a FeatureSet. It ignores duplicate features.
pub fn Add(&mut self, feature: Feature) {
self.Set.insert(feature.0);
}
// HasFeature tests whether or not a feature is in the given feature set.
pub fn HasFeature(&self, feature: Feature) -> bool {
return self.Set.contains(&feature.0)
}
// IsSubset returns true if the FeatureSet is a subset of the FeatureSet passed in.
// This is useful if you want to see if a FeatureSet is compatible with another
// FeatureSet, since you can only run with a given FeatureSet if it's a subset of
// the host's.
pub fn IsSubet(&self, other: &Self) -> bool {
return self.Subtract(other).len() == 0;
}
// Subtract returns the features present in fs that are not present in other.
// If all features in fs are present in other, Subtract returns nil.
pub fn Subtract(&self, other: &Self) -> Vec<Feature> {
let mut diff = Vec::new();
for f in &self.Set {
if !other.Set.contains(f) {
diff.push(Feature(*f))
}
}
return diff
}
pub fn TakeFeatureIntersection(&mut self, other: &Self) {
let mut removes = Vec::with_capacity(self.Set.len());
for f in &self.Set {
if !other.Set.contains(f) {
removes.push(*f)
}
}
for r in removes {
self.Set.remove(&r);
}
}
pub fn EmulateID(&self, origAx: u32, origCx: u32) -> (u32, u32, u32, u32) {
//(ax, bx, cx, dx)
let mut ax: u32 = 0;
let mut bx: u32 = 0;
let mut cx: u32 = 0;
let mut dx: u32 = 0;
if origAx == CpuidFunction::vendorID as u32 {
let ax = CpuidFunction::xSaveInfo as u32;
let (bx, dx, cx) = self.vendorIDRegs();
return (ax, bx, cx, dx)
} else if origAx == CpuidFunction::featureInfo as u32 {
let bx = 8 << 8;
let cx = self.blockMask(0);
let dx = self.blockMask(1);
let ax = self.signature();
return (ax, bx, cx, dx)
} else if origAx == CpuidFunction::intelCacheDescriptors as u32 {
if !self.Intel() {
return (0, 0, 0, 0)
}
ax = 1;
} else if origAx == CpuidFunction::xSaveInfo as u32 {
if !self.UseXsave() {
return (0, 0, 0, 0)
}
return HostID(CpuidFunction::xSaveInfo as u32, origCx)
} else if origAx == CpuidFunction::extendedFeatureInfo as u32 {
if origCx == 0 {
bx = self.blockMask(2);
cx = self.blockMask(3);
}
} else if origAx == ExtendedFunction::extendedFunctionInfo as u32 {
ax = ExtendedFunction::extendedFeatures as u32;
cx = 0;
} else if origAx == ExtendedFunction::extendedFeatures as u32 {
cx = self.blockMask(5);
dx = self.blockMask(6);
if self.AMD() {
dx |= self.blockMask(1) & X86Feature::Block6DuplicateMask as u32
}
} else {
ax = 0;
bx = 0;
cx = 0;
dx = 0;
}
return (ax, bx, cx, dx)
}
pub fn UseXsave(&self) -> bool {
return self.HasFeature(Feature(X86Feature::X86FeatureXSAVE as i32))
&& self.HasFeature(Feature(X86Feature::X86FeatureOSXSAVE as i32))
}
pub fn UseXsaveopt(&self) -> bool {
return self.UseXsave()
&& self.HasFeature(Feature(X86Feature::X86FeatureXSAVEOPT as i32))
}
// CheckHostCompatible returns nil if fs is a subset of the host feature set.
pub fn CheckHostCompatible(&self) -> Result<()> {
let hfs = HostFeatureSet();
let diff = self.Subtract(&hfs);
if diff.len() != 0 {
return Err(Error::Common(format!("CPU feature set {:?} incompatible with host feature set {:?} (missing: {:?})",
self.FlagsString(false), self.FlagsString(false), diff)));
}
return Ok(())
}
// ExtendedStateSize returns the number of bytes needed to save the "extended
// state" for this processor and the boundary it must be aligned to. Extended
// state includes floating point registers, and other cpu state that's not
// associated with the normal task context.
//
// Note: We can save some space here with an optimiazation where we use a
// smaller chunk of memory depending on features that are actually enabled.
// Currently we just use the largest possible size for simplicity (which is
// about 2.5K worst case, with avx512).
pub fn ExtendedStateSize(&self) -> (u32, u32) {
if self.UseXsave() {
// Leaf 0 of xsaveinfo function returns the size for currently
// enabled xsave features in ebx, the maximum size if all valid
// features are saved with xsave in ecx, and valid XCR0 bits in
// edx:eax.
let (_, _, maxSize, _) = HostID(CpuidFunction::xSaveInfo as u32, 0);
return (maxSize as u32, 64)
}
return (512, 16)
}
// ValidXCR0Mask returns the bits that may be set to 1 in control register
// XCR0.
pub fn ValidXCR0Mask(&self) -> u64 {
if !self.UseXsave() {
return 0;
}
let (eax, _, _, edx) = HostID(CpuidFunction::xSaveInfo as u32, 0);
return (edx as u64) << 32 | eax as u64;
}
// vendorIDRegs returns the 3 register values used to construct the 12-byte
// vendor ID string for eax=0.
pub fn vendorIDRegs(&self) -> (u32, u32, u32) {
//(bx, dx, cx)
let mut bx: u32 = 0;
let mut cx: u32 = 0;
let mut dx: u32 = 0;
for i in 0..4 {
bx |= (self.VendorID.as_bytes()[i] as u32) << (i * 8);
}
for i in 0..4 {
dx |= (self.VendorID.as_bytes()[i + 4] as u32) << (i * 8);
}
for i in 0..4 {
cx |= (self.VendorID.as_bytes()[i + 8] as u32) << (i * 8);
}
return (bx, dx, cx)
}
pub fn signature(&self) -> u32 {
let mut s: u32 = 0;
s |= (self.SteppingID & 0xf) as u32;
s |= ((self.Model & 0xf) as u32) << 4;
s |= ((self.Family & 0xf) as u32) << 8;
s |= ((self.ProcessorType & 0x3) as u32) << 12;
s |= ((self.ExtendedModel & 0xf) as u32) << 16;
s |= ((self.ExtendedFamily & 0xf) as u32) << 20;
return s
}
}
fn signatureSplit(v: u32) -> (u8, u8, u8, u8, u8, u8) {
//ef, em, pt, f, m, sid
let sid = (v & 0xf) as u8;
let m = (v >> 4) as u8 & 0xf;
let f = (v >> 8) as u8 & 0xf;
let pt = (v >> 12) as u8 & 0x3;
let em = (v >> 16) as u8 & 0xf;
let ef = (v >> 20) as u8;
return (ef, em, pt, f, m, sid)
}
fn setFromBlockMasks(blocks: &[u32]) -> BTreeSet<i32> {
let mut s = BTreeSet::new();
for b in 0..blocks.len() {
let mut blockMask = blocks[b];
for i in 0..BLOCK_SIZE as usize {
if blockMask & 1 != 0 {
s.insert(featureID(b as i32, i as i32).0);
}
blockMask >>= 1;
}
}
return s;
}
pub fn PrintHostId(axArg: u32, cxArg: u32) {
let (ax, bx, cx, dx) = HostID(axArg, cxArg);
info!("Host({}, {}) => ax = {} bx = {}, cx = {}, dx= {}", axArg, cxArg, ax, bx, cx, dx);
}
pub fn HostID(axArg: u32, cxArg: u32) -> (u32, u32, u32, u32) {
let (ax, bx, cx, dx) = AsmHostID(axArg, cxArg);
return (ax, bx, cx, dx)
}
// HostFeatureSet uses cpuid to get host values and construct a feature set
// that matches that of the host machine. Note that there are several places
// where there appear to be some unnecessary assignments between register names
// (ax, bx, cx, or dx) and featureBlockN variables. This is to explicitly show
// where the different feature blocks come from, to make the code easier to
// inspect and read.
pub fn HostFeatureSet() -> FeatureSet {
let (_, bx, cx, dx) = HostID(0, 0);
let vendorID = vendorIDFromRegs(bx, cx, dx);
let (ax, _, cx, dx) = HostID(1, 0);
let featureBlock0 = cx;
let featureBlock1 = dx;
let (ef, em, pt, f, m, sid) = signatureSplit(ax);
let (_, bx, cx, _) = HostID(7, 0);
let featureBlock2 = bx;
let featureBlock3 = cx;
let mut featureBlock4 = 0;
if (featureBlock0 & (1 << 26)) != 0 {
let (tmp, _, _, _) = HostID(CpuidFunction::xSaveInfo as u32, 1);
featureBlock4 = tmp;
}
let mut featureBlock5 = 0;
let mut featureBlock6 = 0;
let (ax, _, _, _) = HostID(ExtendedFunction::extendedFunctionInfo as u32, 0);
if ax > ExtendedFunction::extendedFunctionInfo as u32 {
let (_, _, cx, dx) = HostID(ExtendedFunction::extendedFeatures as u32, 0);
featureBlock5 = cx;
featureBlock6 = dx & !(X86Feature::Block6DuplicateMask as u32);
}
let set = setFromBlockMasks(&[featureBlock0, featureBlock1, featureBlock2, featureBlock3, featureBlock4, featureBlock5, featureBlock6]);
return FeatureSet {
Set: set,
VendorID: vendorID,
ExtendedFamily: ef,
ExtendedModel: em,
ProcessorType: pt,
Family: f,
Model: m,
SteppingID: sid,
}
}
// Helper to convert 3 regs into 12-byte vendor ID.
fn vendorIDFromRegs(bx: u32, cx: u32, dx: u32) -> String {
let mut bytes: Vec<u8> = Vec::with_capacity(12);
for i in 0..4 {
let b = (bx >> (i * 8)) as u8;
bytes.push(b);
}
for i in 0..4 {
let b = (dx >> (i * 8)) as u8;
bytes.push(b);
}
for i in 0..4 {
let b = (cx >> (i * 8)) as u8;
bytes.push(b);
}
return String::from_utf8(bytes).unwrap()
}
fn initFeaturesFromString() {
let mut map = X86_FEATURES_FROM_STRING.lock();
for (f, s) in &*X86_FEATURE_STRINGS {
map.insert(s.to_string(), *f);
}
for (f, s) in &*X86_FEATURE_PARSE_ONLY_STRINGS {
map.insert(s.to_string(), *f);
}
} |
//! Rust implementation of the `CPU_*` macro API.
#![allow(non_snake_case)]
use super::types::RawCpuSet;
use core::mem::size_of_val;
#[inline]
pub(crate) fn CPU_SET(cpu: usize, cpuset: &mut RawCpuSet) {
let size_in_bits = 8 * size_of_val(&cpuset.bits[0]); // 32, 64 etc
let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits);
cpuset.bits[idx] |= 1 << offset
}
#[inline]
pub(crate) fn CPU_ZERO(cpuset: &mut RawCpuSet) {
cpuset.bits.fill(0)
}
#[inline]
pub(crate) fn CPU_CLR(cpu: usize, cpuset: &mut RawCpuSet) {
let size_in_bits = 8 * size_of_val(&cpuset.bits[0]); // 32, 64 etc
let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits);
cpuset.bits[idx] &= !(1 << offset)
}
#[inline]
pub(crate) fn CPU_ISSET(cpu: usize, cpuset: &RawCpuSet) -> bool {
let size_in_bits = 8 * size_of_val(&cpuset.bits[0]);
let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits);
(cpuset.bits[idx] & (1 << offset)) != 0
}
#[inline]
pub(crate) fn CPU_COUNT_S(size_in_bytes: usize, cpuset: &RawCpuSet) -> u32 {
let size_of_mask = size_of_val(&cpuset.bits[0]);
let idx = size_in_bytes / size_of_mask;
cpuset.bits[..idx]
.iter()
.fold(0, |acc, i| acc + i.count_ones())
}
#[inline]
pub(crate) fn CPU_COUNT(cpuset: &RawCpuSet) -> u32 {
CPU_COUNT_S(core::mem::size_of::<RawCpuSet>(), cpuset)
}
|
// Copyright 2020 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::net::SocketAddr;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use common_base::tokio;
use common_base::tokio::sync::mpsc::Receiver;
use common_exception::Result;
use futures::stream::Abortable;
use futures::Future;
use tokio_stream::wrappers::TcpListenerStream;
use crate::sessions::SessionManagerRef;
pub type ListeningStream = Abortable<TcpListenerStream>;
#[async_trait::async_trait]
pub trait Server {
async fn shutdown(&mut self);
async fn start(&mut self, listening: SocketAddr) -> Result<SocketAddr>;
}
pub struct ShutdownHandle {
shutdown: Arc<AtomicBool>,
sessions: SessionManagerRef,
services: Vec<Box<dyn Server>>,
}
impl ShutdownHandle {
pub fn create(sessions: SessionManagerRef) -> ShutdownHandle {
ShutdownHandle {
services: vec![],
sessions,
shutdown: Arc::new(AtomicBool::new(false)),
}
}
pub fn shutdown(&mut self, signal: Option<Receiver<()>>) -> impl Future<Output = ()> + '_ {
let mut shutdown_jobs = vec![];
for service in &mut self.services {
shutdown_jobs.push(service.shutdown());
}
let sessions = self.sessions.clone();
let join_all = futures::future::join_all(shutdown_jobs);
async move {
let cluster_discovery = sessions.get_cluster_discovery();
cluster_discovery.unregister_to_metastore().await;
join_all.await;
sessions.shutdown(signal).await;
}
}
pub fn wait_for_termination_request(&mut self) -> impl Future<Output = ()> + '_ {
let mut receiver = Self::register_termination_handle();
async move {
receiver.recv().await;
log::info!("Received termination signal.");
log::info!("You can press Ctrl + C again to force shutdown.");
if let Ok(false) =
self.shutdown
.compare_exchange(false, true, Ordering::SeqCst, Ordering::Acquire)
{
let shutdown_services = self.shutdown(Some(receiver));
shutdown_services.await;
}
}
}
pub fn register_termination_handle() -> Receiver<()> {
let (tx, rx) = tokio::sync::mpsc::channel(1);
ctrlc::set_handler(move || {
if let Err(error) = tx.blocking_send(()) {
log::error!("Could not send signal on channel {}", error);
std::process::exit(1);
}
})
.expect("Error setting Ctrl-C handler");
rx
}
pub fn add_service(&mut self, service: Box<dyn Server>) {
self.services.push(service);
}
}
impl Drop for ShutdownHandle {
fn drop(&mut self) {
if let Ok(false) =
self.shutdown
.compare_exchange(false, true, Ordering::SeqCst, Ordering::Acquire)
{
futures::executor::block_on(self.shutdown(None));
}
}
}
|
use super::SharedVars;
use syn::Ident;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum FieldAccessor<'a> {
/// Accessible with `self.field_name`
Direct,
/// Accessible with `fn field_name(&self)->FieldType`
Method { name: Option<&'a Ident> },
/// Accessible with `fn field_name(&self)->Option<FieldType>`
MethodOption,
/// This field is completely inaccessible.
Opaque,
}
impl<'a> FieldAccessor<'a> {
pub(crate) fn compress(self, shared_vars: &mut SharedVars<'a>) -> CompFieldAccessor {
match self {
FieldAccessor::Direct => CompFieldAccessor::DIRECT,
FieldAccessor::Method { name: None } => CompFieldAccessor::METHOD,
FieldAccessor::Method { name: Some(name) } => {
let _ = shared_vars.push_ident(name);
CompFieldAccessor::METHOD_NAMED
}
FieldAccessor::MethodOption => CompFieldAccessor::METHOD_OPTION,
FieldAccessor::Opaque => CompFieldAccessor::OPAQUE,
}
}
}
abi_stable_shared::declare_comp_field_accessor! {
attrs=[]
}
////////////////////////////////////////////////////////////////////////////////
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ModReflMode<T> {
Module,
Opaque,
DelegateDeref(T),
}
|
//! Converts version 1 of the tags (stored in a JSON file) to version 2 of the
//! tag storage (stored in a SQLite3 database).
extern crate rusqlite;
extern crate serde_json;
extern crate walkdir;
use rusqlite::Connection;
use std::collections::BTreeMap;
use std::fs::File;
use std::path::Path;
use walkdir::{WalkDir};
fn main() {
let json_dir = Path::new("./.talked");
if !json_dir.exists() || !json_dir.is_dir() {
panic!("json directory must exist (./.talked)");
}
let walker = WalkDir::new(json_dir.to_str().unwrap()).into_iter();
let conn = Connection::open(Path::new("./database.db"))
.expect("invalid db path");
let mut values = String::new();
for entry in walker {
let entry = entry.unwrap();
let path = entry.path().to_str().expect("Error unwrapping path str");
if !path.ends_with("tags.json") {
continue;
}
let file = File::open(path).unwrap();
let tags: BTreeMap<String, String> = serde_json::from_reader(file)
.unwrap();
let server_id = {
let split_by_s: Vec<&str> = path.split("s").collect();
let split_by_slash: Vec<&str> = split_by_s[1].split("/").collect();
split_by_slash[0]
};
// Since joining strings of vectors in rust is not that easy, just push
// to a string.
for (k, v) in &tags {
values.push_str(&format!("(\"{}\", \"{}\", \"{}\"),", k, server_id, v));
}
}
if !values.is_empty() {
// Remove the last `,` from the string
let _ = values.pop();
let query = format!("INSERT INTO tags (key, server_id, value)
VALUES {}", values);
conn.execute(&query, &[]).expect("Failed to insert query");
}
println!("Query ran");
}
|
pub use self::kt_std::*;
pub mod kt_std;
|
//! Some helpers around Path and PathBuf manipulations.
use super::Result;
use anyhow::anyhow;
use std::path::Path;
use std::path::PathBuf;
/// Wraps the annoying PathBuf to string conversion in one single call.
pub fn path_to_str(path: &PathBuf) -> Result<&str> {
Ok(path
.to_str()
.ok_or(anyhow!("Not a valid UTF-8 path ({})", path.display()))?)
}
/// Finds the path to `to` relative from `from`.
pub fn path_between<P1: AsRef<Path>, P2: AsRef<Path>>(from: P1, to: P2) -> PathBuf {
let mut path = PathBuf::from("/");
for _ in from.as_ref() {
path.push("..");
}
for dir in to.as_ref().iter().skip(1) {
path.push(dir);
}
path
}
|
pub mod break_handler;
|
pub use VkFormat::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkFormat {
VK_FORMAT_UNDEFINED = 0,
VK_FORMAT_R4G4_UNORM_PACK8 = 1,
VK_FORMAT_R4G4B4A4_UNORM_PACK16 = 2,
VK_FORMAT_B4G4R4A4_UNORM_PACK16 = 3,
VK_FORMAT_R5G6B5_UNORM_PACK16 = 4,
VK_FORMAT_B5G6R5_UNORM_PACK16 = 5,
VK_FORMAT_R5G5B5A1_UNORM_PACK16 = 6,
VK_FORMAT_B5G5R5A1_UNORM_PACK16 = 7,
VK_FORMAT_A1R5G5B5_UNORM_PACK16 = 8,
VK_FORMAT_R8_UNORM = 9,
VK_FORMAT_R8_SNORM = 10,
VK_FORMAT_R8_USCALED = 11,
VK_FORMAT_R8_SSCALED = 12,
VK_FORMAT_R8_UINT = 13,
VK_FORMAT_R8_SINT = 14,
VK_FORMAT_R8_SRGB = 15,
VK_FORMAT_R8G8_UNORM = 16,
VK_FORMAT_R8G8_SNORM = 17,
VK_FORMAT_R8G8_USCALED = 18,
VK_FORMAT_R8G8_SSCALED = 19,
VK_FORMAT_R8G8_UINT = 20,
VK_FORMAT_R8G8_SINT = 21,
VK_FORMAT_R8G8_SRGB = 22,
VK_FORMAT_R8G8B8_UNORM = 23,
VK_FORMAT_R8G8B8_SNORM = 24,
VK_FORMAT_R8G8B8_USCALED = 25,
VK_FORMAT_R8G8B8_SSCALED = 26,
VK_FORMAT_R8G8B8_UINT = 27,
VK_FORMAT_R8G8B8_SINT = 28,
VK_FORMAT_R8G8B8_SRGB = 29,
VK_FORMAT_B8G8R8_UNORM = 30,
VK_FORMAT_B8G8R8_SNORM = 31,
VK_FORMAT_B8G8R8_USCALED = 32,
VK_FORMAT_B8G8R8_SSCALED = 33,
VK_FORMAT_B8G8R8_UINT = 34,
VK_FORMAT_B8G8R8_SINT = 35,
VK_FORMAT_B8G8R8_SRGB = 36,
VK_FORMAT_R8G8B8A8_UNORM = 37,
VK_FORMAT_R8G8B8A8_SNORM = 38,
VK_FORMAT_R8G8B8A8_USCALED = 39,
VK_FORMAT_R8G8B8A8_SSCALED = 40,
VK_FORMAT_R8G8B8A8_UINT = 41,
VK_FORMAT_R8G8B8A8_SINT = 42,
VK_FORMAT_R8G8B8A8_SRGB = 43,
VK_FORMAT_B8G8R8A8_UNORM = 44,
VK_FORMAT_B8G8R8A8_SNORM = 45,
VK_FORMAT_B8G8R8A8_USCALED = 46,
VK_FORMAT_B8G8R8A8_SSCALED = 47,
VK_FORMAT_B8G8R8A8_UINT = 48,
VK_FORMAT_B8G8R8A8_SINT = 49,
VK_FORMAT_B8G8R8A8_SRGB = 50,
VK_FORMAT_A8B8G8R8_UNORM_PACK32 = 51,
VK_FORMAT_A8B8G8R8_SNORM_PACK32 = 52,
VK_FORMAT_A8B8G8R8_USCALED_PACK32 = 53,
VK_FORMAT_A8B8G8R8_SSCALED_PACK32 = 54,
VK_FORMAT_A8B8G8R8_UINT_PACK32 = 55,
VK_FORMAT_A8B8G8R8_SINT_PACK32 = 56,
VK_FORMAT_A8B8G8R8_SRGB_PACK32 = 57,
VK_FORMAT_A2R10G10B10_UNORM_PACK32 = 58,
VK_FORMAT_A2R10G10B10_SNORM_PACK32 = 59,
VK_FORMAT_A2R10G10B10_USCALED_PACK32 = 60,
VK_FORMAT_A2R10G10B10_SSCALED_PACK32 = 61,
VK_FORMAT_A2R10G10B10_UINT_PACK32 = 62,
VK_FORMAT_A2R10G10B10_SINT_PACK32 = 63,
VK_FORMAT_A2B10G10R10_UNORM_PACK32 = 64,
VK_FORMAT_A2B10G10R10_SNORM_PACK32 = 65,
VK_FORMAT_A2B10G10R10_USCALED_PACK32 = 66,
VK_FORMAT_A2B10G10R10_SSCALED_PACK32 = 67,
VK_FORMAT_A2B10G10R10_UINT_PACK32 = 68,
VK_FORMAT_A2B10G10R10_SINT_PACK32 = 69,
VK_FORMAT_R16_UNORM = 70,
VK_FORMAT_R16_SNORM = 71,
VK_FORMAT_R16_USCALED = 72,
VK_FORMAT_R16_SSCALED = 73,
VK_FORMAT_R16_UINT = 74,
VK_FORMAT_R16_SINT = 75,
VK_FORMAT_R16_SFLOAT = 76,
VK_FORMAT_R16G16_UNORM = 77,
VK_FORMAT_R16G16_SNORM = 78,
VK_FORMAT_R16G16_USCALED = 79,
VK_FORMAT_R16G16_SSCALED = 80,
VK_FORMAT_R16G16_UINT = 81,
VK_FORMAT_R16G16_SINT = 82,
VK_FORMAT_R16G16_SFLOAT = 83,
VK_FORMAT_R16G16B16_UNORM = 84,
VK_FORMAT_R16G16B16_SNORM = 85,
VK_FORMAT_R16G16B16_USCALED = 86,
VK_FORMAT_R16G16B16_SSCALED = 87,
VK_FORMAT_R16G16B16_UINT = 88,
VK_FORMAT_R16G16B16_SINT = 89,
VK_FORMAT_R16G16B16_SFLOAT = 90,
VK_FORMAT_R16G16B16A16_UNORM = 91,
VK_FORMAT_R16G16B16A16_SNORM = 92,
VK_FORMAT_R16G16B16A16_USCALED = 93,
VK_FORMAT_R16G16B16A16_SSCALED = 94,
VK_FORMAT_R16G16B16A16_UINT = 95,
VK_FORMAT_R16G16B16A16_SINT = 96,
VK_FORMAT_R16G16B16A16_SFLOAT = 97,
VK_FORMAT_R32_UINT = 98,
VK_FORMAT_R32_SINT = 99,
VK_FORMAT_R32_SFLOAT = 100,
VK_FORMAT_R32G32_UINT = 101,
VK_FORMAT_R32G32_SINT = 102,
VK_FORMAT_R32G32_SFLOAT = 103,
VK_FORMAT_R32G32B32_UINT = 104,
VK_FORMAT_R32G32B32_SINT = 105,
VK_FORMAT_R32G32B32_SFLOAT = 106,
VK_FORMAT_R32G32B32A32_UINT = 107,
VK_FORMAT_R32G32B32A32_SINT = 108,
VK_FORMAT_R32G32B32A32_SFLOAT = 109,
VK_FORMAT_R64_UINT = 110,
VK_FORMAT_R64_SINT = 111,
VK_FORMAT_R64_SFLOAT = 112,
VK_FORMAT_R64G64_UINT = 113,
VK_FORMAT_R64G64_SINT = 114,
VK_FORMAT_R64G64_SFLOAT = 115,
VK_FORMAT_R64G64B64_UINT = 116,
VK_FORMAT_R64G64B64_SINT = 117,
VK_FORMAT_R64G64B64_SFLOAT = 118,
VK_FORMAT_R64G64B64A64_UINT = 119,
VK_FORMAT_R64G64B64A64_SINT = 120,
VK_FORMAT_R64G64B64A64_SFLOAT = 121,
VK_FORMAT_B10G11R11_UFLOAT_PACK32 = 122,
VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 = 123,
VK_FORMAT_D16_UNORM = 124,
VK_FORMAT_X8_D24_UNORM_PACK32 = 125,
VK_FORMAT_D32_SFLOAT = 126,
VK_FORMAT_S8_UINT = 127,
VK_FORMAT_D16_UNORM_S8_UINT = 128,
VK_FORMAT_D24_UNORM_S8_UINT = 129,
VK_FORMAT_D32_SFLOAT_S8_UINT = 130,
VK_FORMAT_BC1_RGB_UNORM_BLOCK = 131,
VK_FORMAT_BC1_RGB_SRGB_BLOCK = 132,
VK_FORMAT_BC1_RGBA_UNORM_BLOCK = 133,
VK_FORMAT_BC1_RGBA_SRGB_BLOCK = 134,
VK_FORMAT_BC2_UNORM_BLOCK = 135,
VK_FORMAT_BC2_SRGB_BLOCK = 136,
VK_FORMAT_BC3_UNORM_BLOCK = 137,
VK_FORMAT_BC3_SRGB_BLOCK = 138,
VK_FORMAT_BC4_UNORM_BLOCK = 139,
VK_FORMAT_BC4_SNORM_BLOCK = 140,
VK_FORMAT_BC5_UNORM_BLOCK = 141,
VK_FORMAT_BC5_SNORM_BLOCK = 142,
VK_FORMAT_BC6H_UFLOAT_BLOCK = 143,
VK_FORMAT_BC6H_SFLOAT_BLOCK = 144,
VK_FORMAT_BC7_UNORM_BLOCK = 145,
VK_FORMAT_BC7_SRGB_BLOCK = 146,
VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK = 147,
VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK = 148,
VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK = 149,
VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK = 150,
VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK = 151,
VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK = 152,
VK_FORMAT_EAC_R11_UNORM_BLOCK = 153,
VK_FORMAT_EAC_R11_SNORM_BLOCK = 154,
VK_FORMAT_EAC_R11G11_UNORM_BLOCK = 155,
VK_FORMAT_EAC_R11G11_SNORM_BLOCK = 156,
VK_FORMAT_ASTC_4x4_UNORM_BLOCK = 157,
VK_FORMAT_ASTC_4x4_SRGB_BLOCK = 158,
VK_FORMAT_ASTC_5x4_UNORM_BLOCK = 159,
VK_FORMAT_ASTC_5x4_SRGB_BLOCK = 160,
VK_FORMAT_ASTC_5x5_UNORM_BLOCK = 161,
VK_FORMAT_ASTC_5x5_SRGB_BLOCK = 162,
VK_FORMAT_ASTC_6x5_UNORM_BLOCK = 163,
VK_FORMAT_ASTC_6x5_SRGB_BLOCK = 164,
VK_FORMAT_ASTC_6x6_UNORM_BLOCK = 165,
VK_FORMAT_ASTC_6x6_SRGB_BLOCK = 166,
VK_FORMAT_ASTC_8x5_UNORM_BLOCK = 167,
VK_FORMAT_ASTC_8x5_SRGB_BLOCK = 168,
VK_FORMAT_ASTC_8x6_UNORM_BLOCK = 169,
VK_FORMAT_ASTC_8x6_SRGB_BLOCK = 170,
VK_FORMAT_ASTC_8x8_UNORM_BLOCK = 171,
VK_FORMAT_ASTC_8x8_SRGB_BLOCK = 172,
VK_FORMAT_ASTC_10x5_UNORM_BLOCK = 173,
VK_FORMAT_ASTC_10x5_SRGB_BLOCK = 174,
VK_FORMAT_ASTC_10x6_UNORM_BLOCK = 175,
VK_FORMAT_ASTC_10x6_SRGB_BLOCK = 176,
VK_FORMAT_ASTC_10x8_UNORM_BLOCK = 177,
VK_FORMAT_ASTC_10x8_SRGB_BLOCK = 178,
VK_FORMAT_ASTC_10x10_UNORM_BLOCK = 179,
VK_FORMAT_ASTC_10x10_SRGB_BLOCK = 180,
VK_FORMAT_ASTC_12x10_UNORM_BLOCK = 181,
VK_FORMAT_ASTC_12x10_SRGB_BLOCK = 182,
VK_FORMAT_ASTC_12x12_UNORM_BLOCK = 183,
VK_FORMAT_ASTC_12x12_SRGB_BLOCK = 184,
}
impl From<u32> for VkFormat {
fn from(n: u32) -> Self {
match n {
0 => VK_FORMAT_UNDEFINED,
1 => VK_FORMAT_R4G4_UNORM_PACK8,
2 => VK_FORMAT_R4G4B4A4_UNORM_PACK16,
3 => VK_FORMAT_B4G4R4A4_UNORM_PACK16,
4 => VK_FORMAT_R5G6B5_UNORM_PACK16,
5 => VK_FORMAT_B5G6R5_UNORM_PACK16,
6 => VK_FORMAT_R5G5B5A1_UNORM_PACK16,
7 => VK_FORMAT_B5G5R5A1_UNORM_PACK16,
8 => VK_FORMAT_A1R5G5B5_UNORM_PACK16,
9 => VK_FORMAT_R8_UNORM,
10 => VK_FORMAT_R8_SNORM,
11 => VK_FORMAT_R8_USCALED,
12 => VK_FORMAT_R8_SSCALED,
13 => VK_FORMAT_R8_UINT,
14 => VK_FORMAT_R8_SINT,
15 => VK_FORMAT_R8_SRGB,
16 => VK_FORMAT_R8G8_UNORM,
17 => VK_FORMAT_R8G8_SNORM,
18 => VK_FORMAT_R8G8_USCALED,
19 => VK_FORMAT_R8G8_SSCALED,
20 => VK_FORMAT_R8G8_UINT,
21 => VK_FORMAT_R8G8_SINT,
22 => VK_FORMAT_R8G8_SRGB,
23 => VK_FORMAT_R8G8B8_UNORM,
24 => VK_FORMAT_R8G8B8_SNORM,
25 => VK_FORMAT_R8G8B8_USCALED,
26 => VK_FORMAT_R8G8B8_SSCALED,
27 => VK_FORMAT_R8G8B8_UINT,
28 => VK_FORMAT_R8G8B8_SINT,
29 => VK_FORMAT_R8G8B8_SRGB,
30 => VK_FORMAT_B8G8R8_UNORM,
31 => VK_FORMAT_B8G8R8_SNORM,
32 => VK_FORMAT_B8G8R8_USCALED,
33 => VK_FORMAT_B8G8R8_SSCALED,
34 => VK_FORMAT_B8G8R8_UINT,
35 => VK_FORMAT_B8G8R8_SINT,
36 => VK_FORMAT_B8G8R8_SRGB,
37 => VK_FORMAT_R8G8B8A8_UNORM,
38 => VK_FORMAT_R8G8B8A8_SNORM,
39 => VK_FORMAT_R8G8B8A8_USCALED,
40 => VK_FORMAT_R8G8B8A8_SSCALED,
41 => VK_FORMAT_R8G8B8A8_UINT,
42 => VK_FORMAT_R8G8B8A8_SINT,
43 => VK_FORMAT_R8G8B8A8_SRGB,
44 => VK_FORMAT_B8G8R8A8_UNORM,
45 => VK_FORMAT_B8G8R8A8_SNORM,
46 => VK_FORMAT_B8G8R8A8_USCALED,
47 => VK_FORMAT_B8G8R8A8_SSCALED,
48 => VK_FORMAT_B8G8R8A8_UINT,
49 => VK_FORMAT_B8G8R8A8_SINT,
50 => VK_FORMAT_B8G8R8A8_SRGB,
51 => VK_FORMAT_A8B8G8R8_UNORM_PACK32,
52 => VK_FORMAT_A8B8G8R8_SNORM_PACK32,
53 => VK_FORMAT_A8B8G8R8_USCALED_PACK32,
54 => VK_FORMAT_A8B8G8R8_SSCALED_PACK32,
55 => VK_FORMAT_A8B8G8R8_UINT_PACK32,
56 => VK_FORMAT_A8B8G8R8_SINT_PACK32,
57 => VK_FORMAT_A8B8G8R8_SRGB_PACK32,
58 => VK_FORMAT_A2R10G10B10_UNORM_PACK32,
59 => VK_FORMAT_A2R10G10B10_SNORM_PACK32,
60 => VK_FORMAT_A2R10G10B10_USCALED_PACK32,
61 => VK_FORMAT_A2R10G10B10_SSCALED_PACK32,
62 => VK_FORMAT_A2R10G10B10_UINT_PACK32,
63 => VK_FORMAT_A2R10G10B10_SINT_PACK32,
64 => VK_FORMAT_A2B10G10R10_UNORM_PACK32,
65 => VK_FORMAT_A2B10G10R10_SNORM_PACK32,
66 => VK_FORMAT_A2B10G10R10_USCALED_PACK32,
67 => VK_FORMAT_A2B10G10R10_SSCALED_PACK32,
68 => VK_FORMAT_A2B10G10R10_UINT_PACK32,
69 => VK_FORMAT_A2B10G10R10_SINT_PACK32,
70 => VK_FORMAT_R16_UNORM,
71 => VK_FORMAT_R16_SNORM,
72 => VK_FORMAT_R16_USCALED,
73 => VK_FORMAT_R16_SSCALED,
74 => VK_FORMAT_R16_UINT,
75 => VK_FORMAT_R16_SINT,
76 => VK_FORMAT_R16_SFLOAT,
77 => VK_FORMAT_R16G16_UNORM,
78 => VK_FORMAT_R16G16_SNORM,
79 => VK_FORMAT_R16G16_USCALED,
80 => VK_FORMAT_R16G16_SSCALED,
81 => VK_FORMAT_R16G16_UINT,
82 => VK_FORMAT_R16G16_SINT,
83 => VK_FORMAT_R16G16_SFLOAT,
84 => VK_FORMAT_R16G16B16_UNORM,
85 => VK_FORMAT_R16G16B16_SNORM,
86 => VK_FORMAT_R16G16B16_USCALED,
87 => VK_FORMAT_R16G16B16_SSCALED,
88 => VK_FORMAT_R16G16B16_UINT,
89 => VK_FORMAT_R16G16B16_SINT,
90 => VK_FORMAT_R16G16B16_SFLOAT,
91 => VK_FORMAT_R16G16B16A16_UNORM,
92 => VK_FORMAT_R16G16B16A16_SNORM,
93 => VK_FORMAT_R16G16B16A16_USCALED,
94 => VK_FORMAT_R16G16B16A16_SSCALED,
95 => VK_FORMAT_R16G16B16A16_UINT,
96 => VK_FORMAT_R16G16B16A16_SINT,
97 => VK_FORMAT_R16G16B16A16_SFLOAT,
98 => VK_FORMAT_R32_UINT,
99 => VK_FORMAT_R32_SINT,
100 => VK_FORMAT_R32_SFLOAT,
101 => VK_FORMAT_R32G32_UINT,
102 => VK_FORMAT_R32G32_SINT,
103 => VK_FORMAT_R32G32_SFLOAT,
104 => VK_FORMAT_R32G32B32_UINT,
105 => VK_FORMAT_R32G32B32_SINT,
106 => VK_FORMAT_R32G32B32_SFLOAT,
107 => VK_FORMAT_R32G32B32A32_UINT,
108 => VK_FORMAT_R32G32B32A32_SINT,
109 => VK_FORMAT_R32G32B32A32_SFLOAT,
110 => VK_FORMAT_R64_UINT,
111 => VK_FORMAT_R64_SINT,
112 => VK_FORMAT_R64_SFLOAT,
113 => VK_FORMAT_R64G64_UINT,
114 => VK_FORMAT_R64G64_SINT,
115 => VK_FORMAT_R64G64_SFLOAT,
116 => VK_FORMAT_R64G64B64_UINT,
117 => VK_FORMAT_R64G64B64_SINT,
118 => VK_FORMAT_R64G64B64_SFLOAT,
119 => VK_FORMAT_R64G64B64A64_UINT,
120 => VK_FORMAT_R64G64B64A64_SINT,
121 => VK_FORMAT_R64G64B64A64_SFLOAT,
122 => VK_FORMAT_B10G11R11_UFLOAT_PACK32,
123 => VK_FORMAT_E5B9G9R9_UFLOAT_PACK32,
124 => VK_FORMAT_D16_UNORM,
125 => VK_FORMAT_X8_D24_UNORM_PACK32,
126 => VK_FORMAT_D32_SFLOAT,
127 => VK_FORMAT_S8_UINT,
128 => VK_FORMAT_D16_UNORM_S8_UINT,
129 => VK_FORMAT_D24_UNORM_S8_UINT,
130 => VK_FORMAT_D32_SFLOAT_S8_UINT,
131 => VK_FORMAT_BC1_RGB_UNORM_BLOCK,
132 => VK_FORMAT_BC1_RGB_SRGB_BLOCK,
133 => VK_FORMAT_BC1_RGBA_UNORM_BLOCK,
134 => VK_FORMAT_BC1_RGBA_SRGB_BLOCK,
135 => VK_FORMAT_BC2_UNORM_BLOCK,
136 => VK_FORMAT_BC2_SRGB_BLOCK,
137 => VK_FORMAT_BC3_UNORM_BLOCK,
138 => VK_FORMAT_BC3_SRGB_BLOCK,
139 => VK_FORMAT_BC4_UNORM_BLOCK,
140 => VK_FORMAT_BC4_SNORM_BLOCK,
141 => VK_FORMAT_BC5_UNORM_BLOCK,
142 => VK_FORMAT_BC5_SNORM_BLOCK,
143 => VK_FORMAT_BC6H_UFLOAT_BLOCK,
144 => VK_FORMAT_BC6H_SFLOAT_BLOCK,
145 => VK_FORMAT_BC7_UNORM_BLOCK,
146 => VK_FORMAT_BC7_SRGB_BLOCK,
147 => VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK,
148 => VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK,
149 => VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK,
150 => VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK,
151 => VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK,
152 => VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK,
153 => VK_FORMAT_EAC_R11_UNORM_BLOCK,
154 => VK_FORMAT_EAC_R11_SNORM_BLOCK,
155 => VK_FORMAT_EAC_R11G11_UNORM_BLOCK,
156 => VK_FORMAT_EAC_R11G11_SNORM_BLOCK,
157 => VK_FORMAT_ASTC_4x4_UNORM_BLOCK,
158 => VK_FORMAT_ASTC_4x4_SRGB_BLOCK,
159 => VK_FORMAT_ASTC_5x4_UNORM_BLOCK,
160 => VK_FORMAT_ASTC_5x4_SRGB_BLOCK,
161 => VK_FORMAT_ASTC_5x5_UNORM_BLOCK,
162 => VK_FORMAT_ASTC_5x5_SRGB_BLOCK,
163 => VK_FORMAT_ASTC_6x5_UNORM_BLOCK,
164 => VK_FORMAT_ASTC_6x5_SRGB_BLOCK,
165 => VK_FORMAT_ASTC_6x6_UNORM_BLOCK,
166 => VK_FORMAT_ASTC_6x6_SRGB_BLOCK,
167 => VK_FORMAT_ASTC_8x5_UNORM_BLOCK,
168 => VK_FORMAT_ASTC_8x5_SRGB_BLOCK,
169 => VK_FORMAT_ASTC_8x6_UNORM_BLOCK,
170 => VK_FORMAT_ASTC_8x6_SRGB_BLOCK,
171 => VK_FORMAT_ASTC_8x8_UNORM_BLOCK,
172 => VK_FORMAT_ASTC_8x8_SRGB_BLOCK,
173 => VK_FORMAT_ASTC_10x5_UNORM_BLOCK,
174 => VK_FORMAT_ASTC_10x5_SRGB_BLOCK,
175 => VK_FORMAT_ASTC_10x6_UNORM_BLOCK,
176 => VK_FORMAT_ASTC_10x6_SRGB_BLOCK,
177 => VK_FORMAT_ASTC_10x8_UNORM_BLOCK,
178 => VK_FORMAT_ASTC_10x8_SRGB_BLOCK,
179 => VK_FORMAT_ASTC_10x10_UNORM_BLOCK,
180 => VK_FORMAT_ASTC_10x10_SRGB_BLOCK,
181 => VK_FORMAT_ASTC_12x10_UNORM_BLOCK,
182 => VK_FORMAT_ASTC_12x10_SRGB_BLOCK,
183 => VK_FORMAT_ASTC_12x12_UNORM_BLOCK,
184 => VK_FORMAT_ASTC_12x12_SRGB_BLOCK,
_ => VK_FORMAT_UNDEFINED,
}
}
}
|
// For explanation of lint checks, run `rustc -W help`
// This is adapted from
// https://github.com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md
#![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items,
unknown_crate_types, warnings)]
#![deny(deprecated, drop_with_repr_extern, improper_ctypes, //missing_docs,
non_shorthand_field_patterns, overflowing_literals, plugin_as_library,
private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion,
unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes,
unused_comparisons, unused_features, unused_parens, while_true)]
#![warn(trivial_casts, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results, variant_size_differences)]
#![allow(box_pointers, fat_ptr_transmutes, missing_copy_implementations,
missing_debug_implementations)]
///! # multihash
///!
///! Implementation of [multihash](https://github.com/jbenet/multihash)
///! in Rust.
/// Representation of a Multiaddr.
extern crate sodiumoxide;
extern crate rustc_serialize;
use rustc_serialize::hex::FromHex;
use sodiumoxide::crypto::hash::{sha256, sha512};
use std::io;
pub use self::hashes::*;
pub mod hashes;
/// Encode a string into a multihash
///
/// # Examples
///
/// Simple construction
///
/// ```
/// use multihash::{encode, HashTypes};
///
/// assert_eq!(
/// encode(HashTypes::SHA2256, "hello world").unwrap(),
/// "1220b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
/// );
/// ```
///
pub fn encode(wanttype: HashTypes, input: &str) -> io::Result<String> {
let digest = match wanttype {
HashTypes::SHA2256 => dig_to_vec(&(sha256::hash(input.as_bytes())[..])),
HashTypes::SHA2512 => dig_to_vec(&(sha512::hash(input.as_bytes())[..])),
_ => None,
};
match digest {
Some(digest) => {
let mut bytes = Vec::new();
bytes.push(wanttype.code());
bytes.push(digest.len() as u8);
bytes.extend(digest);
Ok(to_hex(bytes))
},
None => Err(io::Error::new(io::ErrorKind::Other, "Unsupported hash type"))
}
}
/// Encode a string into a multihash
///
/// # Examples
///
/// Simple construction
///
/// ```
/// use multihash::{decode, HashTypes, Multihash};
///
/// assert_eq!(
/// decode("1220b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9").unwrap(),
/// Multihash {
/// alg: HashTypes::SHA2256,
/// digest: "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9",
/// }
/// );
/// ```
///
pub fn decode(input: &str) -> io::Result<Multihash> {
if input.len() > 129 {
return Err(io::Error::new(io::ErrorKind::Other, "Too long"));
}
if input.len() < 3 {
return Err(io::Error::new(io::ErrorKind::Other, "Too short"));
}
let hex_input = input.from_hex();
if hex_input.is_err() {
return Err(io::Error::new(io::ErrorKind::Other, "Failed to parse hex string"));
}
let code = hex_input.unwrap()[0];
match HashTypes::from_code(code) {
Some(alg) => {
Ok(Multihash {
alg: alg,
digest: &input[4..],
})
},
None => {
Err(io::Error::new(io::ErrorKind::Other, format!("Unkown code {:?}", code)))
}
}
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Multihash<'a> {
pub alg: HashTypes,
pub digest: &'a str,
}
/// Convert bytes to a hex representation
fn to_hex(bytes: Vec<u8>) -> String {
bytes.iter().rev().map(|x| {
format!("{:02x}", x)
}).rev().collect()
}
fn dig_to_vec (input: &[u8]) -> Option<Vec<u8>> {
let mut bytes = Vec::new();
bytes.extend(&input[..]);
Some(bytes)
}
|
// xfail-stage0
// -*- rust -*-
use std;
import std._str;
fn main() {
auto s = "hello";
auto sb = _str.rustrt.str_buf(s);
auto s_cstr = _str.rustrt.str_from_cstr(sb);
check (_str.eq(s_cstr, s));
auto s_buf = _str.rustrt.str_from_buf(sb, 5u);
check (_str.eq(s_buf, s));
}
|
use crate::ResponseExt;
use hyper::header::{HeaderValue, ALLOW};
use hyper::{Body, Method as HttpMethod, Request, Response, StatusCode};
#[derive(Debug, Clone)]
pub struct Method {
allow: Vec<HttpMethod>,
}
impl Method {
pub fn new(allow: Vec<HttpMethod>) -> Self {
Self { allow }
}
pub fn response(&self, req: &Request<Body>) -> Option<Response<Body>> {
if !self.allow.contains(req.method()) {
// Show allowed methods in header
if req.method() == HttpMethod::OPTIONS {
let allow = self
.allow
.iter()
.map(|m| m.as_str())
.collect::<Vec<&str>>()
.join(", ");
return Some(
Response::error(StatusCode::METHOD_NOT_ALLOWED)
.header(ALLOW, HeaderValue::from_str(&allow).unwrap()),
);
}
return Some(Response::error(StatusCode::METHOD_NOT_ALLOWED));
}
None
}
}
|
#![deny(clippy::all)]
use anyhow::{anyhow, Result};
use encoding::hex;
pub fn xor(a: &[u8], b: &[u8]) -> Result<Vec<u8>> {
if a.len() != b.len() {
Err(anyhow!("Invalid input, XOR only on two equal length vector"))
} else {
Ok(a.iter().zip(b.iter()).map(|(x, y)| x ^ y).collect())
}
}
/// XOR operation on two hex string of the same length.
pub fn fixed_xor(hex1: &str, hex2: &str) -> Result<String> {
let b1 = hex::hexstr_to_bytes(&hex1)?;
let b2 = hex::hexstr_to_bytes(&hex2)?;
let result_bytes = xor(&b1, &b2)?;
Ok(hex::bytes_to_hexstr(&result_bytes))
}
/// XOR operation on `msg` (hex str) with repeating `key` (also hex str)
pub fn repeating_xor(msg: &str, key: &str) -> String {
let mut result = String::new();
for i in 0..(msg.len() / key.len()) {
result.push_str(&fixed_xor(&msg[i * key.len()..(i + 1) * key.len()], &key[..]).unwrap());
}
// dealing with remainder
let remainder_len = msg.len() % key.len();
result.push_str(&fixed_xor(&msg[msg.len() - remainder_len..], &key[0..remainder_len]).unwrap());
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fixed_xor() {
assert_eq!(
fixed_xor(
"1c0111001f010100061a024b53535009181c",
"686974207468652062756c6c277320657965"
)
.unwrap(),
String::from("746865206b696420646f6e277420706c6179"),
);
assert!(fixed_xor("12", "3").is_err());
}
#[test]
fn test_repeating_xor() {
let msg_hex = hex::bytes_to_hexstr(
&"Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal".as_bytes(),
);
let key_hex = hex::bytes_to_hexstr(b"ICE");
assert_eq!(
repeating_xor(&msg_hex, &key_hex),
"0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.