Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs
This commit is contained in:
Vendored
+308
@@ -0,0 +1,308 @@
|
||||
//! The [`Generator`] trait and [`BlockRng`]
|
||||
//!
|
||||
//! Trait [`Generator`] may be implemented by block-generators; that is PRNGs
|
||||
//! whose output is a *block* of words, such as `[u32; 16]`.
|
||||
//!
|
||||
//! The struct [`BlockRng`] wraps such a [`Generator`] together with an output
|
||||
//! buffer and implements several methods (e.g. [`BlockRng::next_word`]) to
|
||||
//! assist in the implementation of [`TryRng`]. Note that (unlike in earlier
|
||||
//! versions of `rand_core`) [`BlockRng`] itself does not implement [`TryRng`]
|
||||
//! since in practice we found it was always beneficial to use a wrapper type
|
||||
//! over [`BlockRng`].
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```
|
||||
//! use core::convert::Infallible;
|
||||
//! use rand_core::{Rng, SeedableRng, TryRng};
|
||||
//! use rand_core::block::{Generator, BlockRng};
|
||||
//!
|
||||
//! struct MyRngCore {
|
||||
//! // Generator state ...
|
||||
//! # state: [u32; 8],
|
||||
//! }
|
||||
//!
|
||||
//! impl Generator for MyRngCore {
|
||||
//! type Output = [u32; 8];
|
||||
//!
|
||||
//! fn generate(&mut self, output: &mut Self::Output) {
|
||||
//! // Write a new block to output...
|
||||
//! # *output = self.state;
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! // Our RNG is a wrapper over BlockRng
|
||||
//! pub struct MyRng(BlockRng<MyRngCore>);
|
||||
//!
|
||||
//! impl SeedableRng for MyRng {
|
||||
//! type Seed = [u8; 32];
|
||||
//! fn from_seed(seed: Self::Seed) -> Self {
|
||||
//! let core = MyRngCore {
|
||||
//! // ...
|
||||
//! # state: rand_core::utils::read_words(&seed),
|
||||
//! };
|
||||
//! MyRng(BlockRng::new(core))
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! impl TryRng for MyRng {
|
||||
//! type Error = Infallible;
|
||||
//!
|
||||
//! #[inline]
|
||||
//! fn try_next_u32(&mut self) -> Result<u32, Infallible> {
|
||||
//! Ok(self.0.next_word())
|
||||
//! }
|
||||
//!
|
||||
//! #[inline]
|
||||
//! fn try_next_u64(&mut self) -> Result<u64, Infallible> {
|
||||
//! Ok(self.0.next_u64_from_u32())
|
||||
//! }
|
||||
//!
|
||||
//! #[inline]
|
||||
//! fn try_fill_bytes(&mut self, bytes: &mut [u8]) -> Result<(), Infallible> {
|
||||
//! Ok(self.0.fill_bytes(bytes))
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! // And if applicable: impl TryCryptoRng for MyRng {}
|
||||
//!
|
||||
//! let mut rng = MyRng::seed_from_u64(0);
|
||||
//! println!("First value: {}", rng.next_u32());
|
||||
//! # assert_eq!(rng.next_u32(), 1171109249);
|
||||
//! ```
|
||||
//!
|
||||
//! [`TryRng`]: crate::TryRng
|
||||
//! [`SeedableRng`]: crate::SeedableRng
|
||||
|
||||
use crate::utils::Word;
|
||||
use core::fmt;
|
||||
|
||||
/// A random (block) generator
|
||||
pub trait Generator {
|
||||
/// The output type.
|
||||
///
|
||||
/// For use with [`rand_core::block`](crate::block) code this must be `[u32; _]` or `[u64; _]`.
|
||||
type Output;
|
||||
|
||||
/// Generate a new block of `output`.
|
||||
///
|
||||
/// This must fill `output` with random data.
|
||||
fn generate(&mut self, output: &mut Self::Output);
|
||||
|
||||
/// Destruct the output buffer
|
||||
///
|
||||
/// This method is called on [`Drop`] of the [`Self::Output`] buffer.
|
||||
/// The default implementation does nothing.
|
||||
#[inline]
|
||||
fn drop(&mut self, output: &mut Self::Output) {
|
||||
let _ = output;
|
||||
}
|
||||
}
|
||||
|
||||
/// RNG functionality for a block [`Generator`]
|
||||
///
|
||||
/// This type encompasses a [`Generator`] [`core`](Self::core) and a buffer.
|
||||
/// It provides optimized implementations of methods required by an [`Rng`].
|
||||
///
|
||||
/// All values are consumed in-order of generation. No whole words (e.g. `u32`
|
||||
/// or `u64`) are discarded, though where a word is partially used (e.g. for a
|
||||
/// byte-fill whose length is not a multiple of the word size) the rest of the
|
||||
/// word is discarded.
|
||||
///
|
||||
/// [`Rng`]: crate::Rng
|
||||
#[derive(Clone)]
|
||||
pub struct BlockRng<G: Generator> {
|
||||
results: G::Output,
|
||||
/// The *core* part of the RNG, implementing the `generate` function.
|
||||
pub core: G,
|
||||
}
|
||||
|
||||
// Custom Debug implementation that does not expose the contents of `results`.
|
||||
impl<G> fmt::Debug for BlockRng<G>
|
||||
where
|
||||
G: Generator + fmt::Debug,
|
||||
{
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
fmt.debug_struct("BlockRng")
|
||||
.field("core", &self.core)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<G: Generator> Drop for BlockRng<G> {
|
||||
fn drop(&mut self) {
|
||||
self.core.drop(&mut self.results);
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Word + Default, const N: usize, G: Generator<Output = [W; N]>> BlockRng<G> {
|
||||
/// Create a new `BlockRng` from an existing RNG implementing
|
||||
/// `Generator`. Results will be generated on first use.
|
||||
#[inline]
|
||||
pub fn new(core: G) -> BlockRng<G> {
|
||||
let mut results = [W::default(); N];
|
||||
results[0] = W::from_usize(N);
|
||||
BlockRng { core, results }
|
||||
}
|
||||
|
||||
/// Reconstruct from a core and a remaining-results buffer.
|
||||
///
|
||||
/// This may be used to deserialize using a `core` and the output of
|
||||
/// [`Self::remaining_results`].
|
||||
///
|
||||
/// Returns `None` if `remaining_results` is too long.
|
||||
pub fn reconstruct(core: G, remaining_results: &[W]) -> Option<Self> {
|
||||
let mut results = [W::default(); N];
|
||||
if remaining_results.len() < N {
|
||||
let index = N - remaining_results.len();
|
||||
results[index..].copy_from_slice(remaining_results);
|
||||
results[0] = W::from_usize(index);
|
||||
Some(BlockRng { results, core })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Word, const N: usize, G: Generator<Output = [W; N]>> BlockRng<G> {
|
||||
/// Get the index into the result buffer.
|
||||
///
|
||||
/// If this is equal to or larger than the size of the result buffer then
|
||||
/// the buffer is "empty" and `generate()` must be called to produce new
|
||||
/// results.
|
||||
#[inline(always)]
|
||||
fn index(&self) -> usize {
|
||||
self.results[0].into_usize()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn set_index(&mut self, index: usize) {
|
||||
debug_assert!(0 < index && index <= N);
|
||||
self.results[0] = W::from_usize(index);
|
||||
}
|
||||
|
||||
/// Re-generate buffer contents, skipping the first `n` words
|
||||
///
|
||||
/// Existing buffer contents are discarded. A new set of results is
|
||||
/// generated (either immediately or when next required). The first `n`
|
||||
/// words are skipped (this may be used to set a specific word position).
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method will panic if `n >= N` where `N` is the buffer size (in
|
||||
/// words).
|
||||
#[inline]
|
||||
pub fn reset_and_skip(&mut self, n: usize) {
|
||||
if n == 0 {
|
||||
self.set_index(N);
|
||||
return;
|
||||
}
|
||||
|
||||
assert!(n < N);
|
||||
self.core.generate(&mut self.results);
|
||||
self.set_index(n);
|
||||
}
|
||||
|
||||
/// Get the number of words consumed since the start of the block
|
||||
///
|
||||
/// The result is in the range `0..N` where `N` is the buffer size (in
|
||||
/// words).
|
||||
#[inline]
|
||||
pub fn word_offset(&self) -> usize {
|
||||
let index = self.index();
|
||||
if index >= N { 0 } else { index }
|
||||
}
|
||||
|
||||
/// Access the unused part of the results buffer
|
||||
///
|
||||
/// The length of the returned slice is guaranteed to be less than the
|
||||
/// length of `<Self as Generator>::Output` (i.e. less than `N` where
|
||||
/// `Output = [W; N]`).
|
||||
///
|
||||
/// This is a low-level interface intended for serialization.
|
||||
/// Results are not marked as consumed.
|
||||
#[inline]
|
||||
pub fn remaining_results(&self) -> &[W] {
|
||||
let index = self.index();
|
||||
&self.results[index..]
|
||||
}
|
||||
|
||||
/// Generate the next word (e.g. `u32`)
|
||||
#[inline]
|
||||
pub fn next_word(&mut self) -> W {
|
||||
let mut index = self.index();
|
||||
if index >= N {
|
||||
self.core.generate(&mut self.results);
|
||||
index = 0;
|
||||
}
|
||||
|
||||
let value = self.results[index];
|
||||
self.set_index(index + 1);
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize, G: Generator<Output = [u32; N]>> BlockRng<G> {
|
||||
/// Generate a `u64` from two `u32` words
|
||||
#[inline]
|
||||
pub fn next_u64_from_u32(&mut self) -> u64 {
|
||||
let index = self.index();
|
||||
let mut new_index;
|
||||
let (mut lo, mut hi);
|
||||
if index < N - 1 {
|
||||
lo = self.results[index];
|
||||
hi = self.results[index + 1];
|
||||
new_index = index + 2;
|
||||
} else {
|
||||
lo = self.results[N - 1];
|
||||
self.core.generate(&mut self.results);
|
||||
hi = self.results[0];
|
||||
new_index = 1;
|
||||
if index >= N {
|
||||
lo = hi;
|
||||
hi = self.results[1];
|
||||
new_index = 2;
|
||||
}
|
||||
}
|
||||
self.set_index(new_index);
|
||||
(u64::from(hi) << 32) | u64::from(lo)
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Word, const N: usize, G: Generator<Output = [W; N]>> BlockRng<G> {
|
||||
/// Fill `dest`
|
||||
#[inline]
|
||||
pub fn fill_bytes(&mut self, dest: &mut [u8]) {
|
||||
let mut read_len = 0;
|
||||
let mut index = self.index();
|
||||
while read_len < dest.len() {
|
||||
if index >= N {
|
||||
self.core.generate(&mut self.results);
|
||||
index = 0;
|
||||
}
|
||||
|
||||
let size = core::mem::size_of::<W>();
|
||||
let mut chunks = dest[read_len..].chunks_exact_mut(size);
|
||||
let mut src = self.results[index..].iter();
|
||||
|
||||
let zipped = chunks.by_ref().zip(src.by_ref());
|
||||
let num_chunks = zipped.len();
|
||||
zipped.for_each(|(chunk, src)| chunk.copy_from_slice(src.to_le_bytes().as_ref()));
|
||||
index += num_chunks;
|
||||
read_len += num_chunks * size;
|
||||
|
||||
if let Some(src) = src.next() {
|
||||
// We have consumed all full chunks of dest, but not src.
|
||||
let dest_rem = chunks.into_remainder();
|
||||
let n = dest_rem.len();
|
||||
if n > 0 {
|
||||
dest_rem.copy_from_slice(&src.to_le_bytes().as_ref()[..n]);
|
||||
index += 1;
|
||||
debug_assert_eq!(read_len + n, dest.len());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.set_index(index);
|
||||
}
|
||||
}
|
||||
Vendored
+272
@@ -0,0 +1,272 @@
|
||||
// Hide badges from generated docs
|
||||
//! <style> .badges { display: none; } </style>
|
||||
|
||||
#![no_std]
|
||||
#![doc = include_str!("../README.md")]
|
||||
#![doc(
|
||||
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
|
||||
html_favicon_url = "https://www.rust-lang.org/favicon.ico"
|
||||
)]
|
||||
|
||||
use core::ops::DerefMut;
|
||||
|
||||
pub use core::convert::Infallible;
|
||||
|
||||
pub mod block;
|
||||
pub mod utils;
|
||||
|
||||
mod seedable_rng;
|
||||
mod unwrap_err;
|
||||
mod word;
|
||||
|
||||
pub use seedable_rng::SeedableRng;
|
||||
pub use unwrap_err::UnwrapErr;
|
||||
|
||||
/// Trait for infallible random number generators
|
||||
///
|
||||
/// `Rng` is a sub-trait of [`TryRng`] for infallible generators.
|
||||
///
|
||||
/// # Requirements
|
||||
///
|
||||
/// See [`TryRng`#Requirements] which also apply here.
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// The [`rand`] crate provides higher level functionality, for example
|
||||
/// generation of floating-point values, uniform ranged sampling and shuffling
|
||||
/// sequences. In particular, [`rand::RngExt`] is an extension trait over `Rng`
|
||||
/// providing many of the methods one might expect to be able to use on an RNG.
|
||||
///
|
||||
/// # Implementing `Rng`
|
||||
///
|
||||
/// Implement [`TryRng`] with <code>type Error = [core::convert::Infallible][]</code>.
|
||||
///
|
||||
/// [`rand`]: https://docs.rs/rand/
|
||||
/// [`rand::RngExt`]: https://docs.rs/rand/latest/rand/trait.RngExt.html
|
||||
/// [`fill_bytes`]: Rng::fill_bytes
|
||||
/// [`next_u32`]: Rng::next_u32
|
||||
/// [`next_u64`]: Rng::next_u64
|
||||
pub trait Rng: TryRng<Error = Infallible> {
|
||||
/// Return the next random `u32`.
|
||||
fn next_u32(&mut self) -> u32;
|
||||
|
||||
/// Return the next random `u64`.
|
||||
fn next_u64(&mut self) -> u64;
|
||||
|
||||
/// Fill `dest` with random data.
|
||||
///
|
||||
/// This method should guarantee that `dest` is entirely filled
|
||||
/// with new data, and may panic if this is impossible
|
||||
/// (e.g. reading past the end of a file that is being used as the
|
||||
/// source of randomness).
|
||||
fn fill_bytes(&mut self, dst: &mut [u8]);
|
||||
}
|
||||
|
||||
impl<R> Rng for R
|
||||
where
|
||||
R: TryRng<Error = Infallible> + ?Sized,
|
||||
{
|
||||
#[inline]
|
||||
fn next_u32(&mut self) -> u32 {
|
||||
match self.try_next_u32() {
|
||||
Ok(x) => x,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn next_u64(&mut self) -> u64 {
|
||||
match self.try_next_u64() {
|
||||
Ok(x) => x,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn fill_bytes(&mut self, dst: &mut [u8]) {
|
||||
match self.try_fill_bytes(dst) {
|
||||
Ok(()) => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A marker trait for securely unpredictable infallible RNGs
|
||||
///
|
||||
/// This is a convenient trait alias for <code>[TryCryptoRng]<Error = [Infallible]></code>.
|
||||
/// It is equivalent to the trait sum <code>[Rng] + [TryCryptoRng]</code>.
|
||||
pub trait CryptoRng: Rng + TryCryptoRng<Error = Infallible> {}
|
||||
|
||||
impl<R> CryptoRng for R where R: TryCryptoRng<Error = Infallible> + ?Sized {}
|
||||
|
||||
/// Base trait for random number generators and random data sources
|
||||
///
|
||||
/// This trait provides a base interface designed to support efficient usage of
|
||||
/// (`u32`, `u64`) word generators, block generators and random data sources.
|
||||
/// There is no required relationship between the output of each method or any
|
||||
/// requirement to use all generated random bits; for example an implementation
|
||||
/// of [`try_fill_bytes`](Self::try_fill_bytes) may discard some generated bytes
|
||||
/// to avoid storing a partially used word or block.
|
||||
///
|
||||
/// # Requirements
|
||||
///
|
||||
/// ### Quality and length
|
||||
///
|
||||
/// Implementions should produce bits uniformly: each output value should be
|
||||
/// equally likely, without observable patterns in successive outputs or
|
||||
/// between the output streams of multiple instances of an implementation using
|
||||
/// different seeds or streams (where supported by the implementation).
|
||||
///
|
||||
/// Pathological implementations (e.g. constant or counting generators which
|
||||
/// rarely change some bits) may cause issues in consumers of random data, for
|
||||
/// example dead-locks in rejection samplers and obviously non-random output
|
||||
/// (e.g. a counting generator may result in apparently-constant output from a
|
||||
/// uniform-ranged distribution).
|
||||
///
|
||||
/// Cryptographically unpredictable output is not a requirement of this trait,
|
||||
/// but is a requirement of [`TryCryptoRng`].
|
||||
///
|
||||
/// In practice, most implementations are pseudo-random number generators with a
|
||||
/// finite *period* or *cycle length*, and (among non-cryptographic PRNGs)
|
||||
/// statistical anomalies may appear long before a cycle occurs. An
|
||||
/// implementation should ensure its period is sufficiently long that no
|
||||
/// anomalies are likely to appear in usage and/or document its limitations.
|
||||
///
|
||||
/// For more on PRNG quality and period, see [The Rust Rand Book: Quality][0].
|
||||
///
|
||||
/// [0]: https://rust-random.github.io/book/guide-rngs.html#quality
|
||||
///
|
||||
/// ### Reproducibility
|
||||
///
|
||||
/// Algorithmic generators implementing [`SeedableRng`] should normally have
|
||||
/// *portable, reproducible* output, i.e. fix Endianness when converting values
|
||||
/// to avoid platform differences, and avoid making any changes which affect
|
||||
/// output (except by communicating that the release has breaking changes).
|
||||
/// See also [The Rust Rand Book: Reproducibility][1].
|
||||
///
|
||||
/// [1]: https://rust-random.github.io/book/crate-reprod.html
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// Often, usage of the infallible trait [`Rng`] or its extension trait
|
||||
/// [`rand::RngExt`] is preferred to direct usage of `TryRng`.
|
||||
//
|
||||
/// Many implementations of `TryRng` (those with <code>type Error = [Infallible][]</code>)
|
||||
/// already implement [`Rng`]; in other cases [`UnwrapErr`] may be used to obtain
|
||||
/// an implementation of [`Rng`].
|
||||
///
|
||||
/// # Implementing `TryRng`
|
||||
///
|
||||
/// Most algorithmic generators (i.e. pseudo-random number generators or PRNGs)
|
||||
/// never fail; in this case type `Error` should be [`Infallible`]; in this case
|
||||
/// trait `Rng` is implemented automatically. Cycling is not considered an
|
||||
/// error.
|
||||
///
|
||||
/// Small PRNGs often yield either `u32` or `u64` natively.
|
||||
/// Module [`crate::utils`] provides utilities to help implement other methods.
|
||||
///
|
||||
/// Byte sources may implement [`try_fill_bytes`](Self::try_fill_bytes)
|
||||
/// natively.
|
||||
/// Module [`crate::utils`] provides utilities to help implement other methods.
|
||||
///
|
||||
/// Block generators (which produce `[u32; N]` or `[u64; N]` for some fixed `N`)
|
||||
/// should make use of the [`crate::block`] module.
|
||||
///
|
||||
/// With regards to other traits:
|
||||
///
|
||||
/// - **Do not** implement [`Default`] for seedable pseudorandom generators,
|
||||
/// though the trait may be implemented for stateless interfaces and
|
||||
/// auto-seeding generators.
|
||||
/// - **Do** implement [`SeedableRng`] for seedable pseudorandom generators. See
|
||||
/// [Reproducibility](#reproducibility) above.
|
||||
/// - Implement [`Clone`] for non-cryptographic PRNGs but consider not doing so
|
||||
/// for cryptographic generators to avoid the risk of key-stream duplication.
|
||||
/// - **Do not** implement [`Copy`] since accidental copies may cause repeated
|
||||
/// values.
|
||||
/// - Implement [`Debug`](core::fmt::Debug), except that cryptographic PRNGs
|
||||
/// should use a custom implementation which avoids leaking internal state (or
|
||||
/// the subset of this derived from the key).
|
||||
/// - [`Eq`] and [`PartialEq`] could be implemented, but are probably not useful.
|
||||
///
|
||||
/// [`rand::RngExt`]: https://docs.rs/rand/latest/rand/trait.RngExt.html
|
||||
pub trait TryRng {
|
||||
/// The type returned in the event of a RNG error.
|
||||
///
|
||||
/// Use type [`Infallible`] (re-exported by `rand_core`) for infallible implementations.
|
||||
type Error: core::error::Error;
|
||||
|
||||
/// Return the next random `u32`.
|
||||
fn try_next_u32(&mut self) -> Result<u32, Self::Error>;
|
||||
/// Return the next random `u64`.
|
||||
fn try_next_u64(&mut self) -> Result<u64, Self::Error>;
|
||||
/// Fill `dst` entirely with random data.
|
||||
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error>;
|
||||
}
|
||||
|
||||
impl<R: DerefMut> TryRng for R
|
||||
where
|
||||
R::Target: TryRng,
|
||||
{
|
||||
type Error = <R::Target as TryRng>::Error;
|
||||
|
||||
#[inline]
|
||||
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
|
||||
self.deref_mut().try_next_u32()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
|
||||
self.deref_mut().try_next_u64()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
|
||||
self.deref_mut().try_fill_bytes(dst)
|
||||
}
|
||||
}
|
||||
|
||||
/// A marker trait over [`TryRng`] for securely unpredictable RNGs
|
||||
///
|
||||
/// This marker trait indicates that the implementing generator is intended,
|
||||
/// when correctly seeded and protected from side-channel attacks such as a
|
||||
/// leaking of state, to be a cryptographically secure generator. This trait is
|
||||
/// provided as a tool to aid review of cryptographic code, but does not by
|
||||
/// itself guarantee suitability for cryptographic applications.
|
||||
///
|
||||
/// Formally, a CSPRNG (Cryptographically Secure Pseudo-Random Number Generator)
|
||||
/// should satisfy an additional property over other generators: assuming that
|
||||
/// the generator has been appropriately seeded and has unknown state, then
|
||||
/// given the first *k* bits of an algorithm's output
|
||||
/// sequence, it should not be possible using polynomial-time algorithms to
|
||||
/// predict the next bit with probability significantly greater than 50%.
|
||||
///
|
||||
/// An optional property of CSPRNGs is backtracking resistance: if the CSPRNG's
|
||||
/// state is revealed, it will not be computationally-feasible to reconstruct
|
||||
/// prior output values. This property is not required by `CryptoRng`.
|
||||
///
|
||||
/// Implementors of `TryCryptoRng` should only implement [`Default`] if a
|
||||
/// default-constructed instance is itself a secure generator, for example
|
||||
/// [`getrandom::SysRng`] which is a stateless interface.
|
||||
///
|
||||
/// [`getrandom::SysRng`]: https://docs.rs/getrandom/latest/getrandom/struct.SysRng.html
|
||||
pub trait TryCryptoRng: TryRng {}
|
||||
|
||||
impl<R: DerefMut> TryCryptoRng for R where R::Target: TryCryptoRng {}
|
||||
|
||||
/// DEPRECATED: stub trait to print a deprecation warning and aid discovering that [`Rng`] is the
|
||||
/// replacement.
|
||||
// TODO: remove prior to v1.x.
|
||||
#[deprecated(since = "0.10.0", note = "use `Rng` instead")]
|
||||
pub trait RngCore: Rng {}
|
||||
#[allow(deprecated)]
|
||||
impl<R: Rng> RngCore for R {}
|
||||
|
||||
/// DEPRECATED: stub trait to print a deprecation warning and aid discovering that [`TryRng`] is the
|
||||
/// replacement.
|
||||
// TODO: remove prior to v1.x.
|
||||
#[deprecated(since = "0.10.0", note = "use `TryRng` instead")]
|
||||
pub trait TryRngCore: TryRng {
|
||||
/// Error type.
|
||||
type Error: core::error::Error;
|
||||
}
|
||||
#[allow(deprecated)]
|
||||
impl<R: TryRng> TryRngCore for R {
|
||||
type Error = R::Error;
|
||||
}
|
||||
Vendored
+206
@@ -0,0 +1,206 @@
|
||||
use crate::{Rng, TryRng};
|
||||
|
||||
/// A random number generator that can be explicitly seeded.
|
||||
///
|
||||
/// This trait encapsulates the low-level functionality common to all
|
||||
/// pseudo-random number generators (PRNGs, or algorithmic generators).
|
||||
///
|
||||
/// A generator implementing `SeedableRng` will usually be deterministic, but
|
||||
/// beware that portability and reproducibility of results **is not implied**.
|
||||
/// Refer to documentation of the generator, noting that generators named after
|
||||
/// a specific algorithm are usually tested for reproducibility against a
|
||||
/// reference vector, while `SmallRng` and `StdRng` specifically opt out of
|
||||
/// reproducibility guarantees.
|
||||
pub trait SeedableRng: Sized {
|
||||
/// Seed type, which is restricted to types mutably-dereferenceable as `u8`
|
||||
/// arrays (we recommend `[u8; N]` for some `N`).
|
||||
///
|
||||
/// It is recommended to seed PRNGs with a seed of at least circa 100 bits,
|
||||
/// which means an array of `[u8; 12]` or greater to avoid picking RNGs with
|
||||
/// partially overlapping periods.
|
||||
///
|
||||
/// For cryptographic RNG's a seed of 256 bits is recommended, `[u8; 32]`.
|
||||
///
|
||||
///
|
||||
/// # Implementing `SeedableRng` for RNGs with large seeds
|
||||
///
|
||||
/// Note that [`Default`] is not implemented for large arrays `[u8; N]` with
|
||||
/// `N` > 32. To be able to implement the traits required by `SeedableRng`
|
||||
/// for RNGs with such large seeds, the newtype pattern can be used:
|
||||
///
|
||||
/// ```
|
||||
/// use rand_core::SeedableRng;
|
||||
///
|
||||
/// const N: usize = 64;
|
||||
/// #[derive(Clone)]
|
||||
/// pub struct MyRngSeed(pub [u8; N]);
|
||||
/// # #[allow(dead_code)]
|
||||
/// pub struct MyRng(MyRngSeed);
|
||||
///
|
||||
/// impl Default for MyRngSeed {
|
||||
/// fn default() -> MyRngSeed {
|
||||
/// MyRngSeed([0; N])
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// impl AsRef<[u8]> for MyRngSeed {
|
||||
/// fn as_ref(&self) -> &[u8] {
|
||||
/// &self.0
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// impl AsMut<[u8]> for MyRngSeed {
|
||||
/// fn as_mut(&mut self) -> &mut [u8] {
|
||||
/// &mut self.0
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// impl SeedableRng for MyRng {
|
||||
/// type Seed = MyRngSeed;
|
||||
///
|
||||
/// fn from_seed(seed: MyRngSeed) -> MyRng {
|
||||
/// MyRng(seed)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
type Seed: Clone + Default + AsRef<[u8]> + AsMut<[u8]>;
|
||||
|
||||
/// Create a new PRNG using the given seed.
|
||||
///
|
||||
/// PRNG implementations are allowed to assume that bits in the seed are
|
||||
/// well distributed. That means usually that the number of one and zero
|
||||
/// bits are roughly equal, and values like 0, 1 and (size - 1) are unlikely.
|
||||
/// Note that many non-cryptographic PRNGs will show poor quality output
|
||||
/// if this is not adhered to. If you wish to seed from simple numbers, use
|
||||
/// `seed_from_u64` instead.
|
||||
///
|
||||
/// All PRNG implementations should be reproducible unless otherwise noted:
|
||||
/// given a fixed `seed`, the same sequence of output should be produced
|
||||
/// on all runs, library versions and architectures (e.g. check endianness).
|
||||
/// Any "value-breaking" changes to the generator should require bumping at
|
||||
/// least the minor version and documentation of the change.
|
||||
///
|
||||
/// It is not required that this function yield the same state as a
|
||||
/// reference implementation of the PRNG given equivalent seed; if necessary
|
||||
/// another constructor replicating behaviour from a reference
|
||||
/// implementation can be added.
|
||||
///
|
||||
/// PRNG implementations should make sure `from_seed` never panics. In the
|
||||
/// case that some special values (like an all zero seed) are not viable
|
||||
/// seeds it is preferable to map these to alternative constant value(s),
|
||||
/// for example `0xBAD5EEDu32` or `0x0DDB1A5E5BAD5EEDu64` ("odd biases? bad
|
||||
/// seed"). This is assuming only a small number of values must be rejected.
|
||||
fn from_seed(seed: Self::Seed) -> Self;
|
||||
|
||||
/// Create a new PRNG using a `u64` seed.
|
||||
///
|
||||
/// This is a convenience-wrapper around `from_seed` to allow construction
|
||||
/// of any `SeedableRng` from a simple `u64` value. It is designed such that
|
||||
/// low Hamming Weight numbers like 0 and 1 can be used and should still
|
||||
/// result in good, independent seeds to the PRNG which is returned.
|
||||
///
|
||||
/// This **is not suitable for cryptography**, as should be clear given that
|
||||
/// the input size is only 64 bits.
|
||||
///
|
||||
/// Implementations for PRNGs *may* provide their own implementations of
|
||||
/// this function, but the default implementation should be good enough for
|
||||
/// all purposes. *Changing* the implementation of this function should be
|
||||
/// considered a value-breaking change.
|
||||
fn seed_from_u64(mut state: u64) -> Self {
|
||||
let mut seed = Self::Seed::default();
|
||||
let mut iter = seed.as_mut().chunks_exact_mut(4);
|
||||
for chunk in &mut iter {
|
||||
chunk.copy_from_slice(&pcg32(&mut state));
|
||||
}
|
||||
let rem = iter.into_remainder();
|
||||
if !rem.is_empty() {
|
||||
rem.copy_from_slice(&pcg32(&mut state)[..rem.len()]);
|
||||
}
|
||||
|
||||
Self::from_seed(seed)
|
||||
}
|
||||
|
||||
/// Create a new PRNG seeded from an infallible `Rng`.
|
||||
///
|
||||
/// This may be useful when needing to rapidly seed many PRNGs from a master
|
||||
/// PRNG, and to allow forking of PRNGs. It may be considered deterministic.
|
||||
///
|
||||
/// The master PRNG should be at least as high quality as the child PRNGs.
|
||||
/// When seeding non-cryptographic child PRNGs, we recommend using a
|
||||
/// different algorithm for the master PRNG (ideally a CSPRNG) to avoid
|
||||
/// correlations between the child PRNGs. If this is not possible (e.g.
|
||||
/// forking using small non-crypto PRNGs) ensure that your PRNG has a good
|
||||
/// mixing function on the output or consider use of a hash function with
|
||||
/// `from_seed`.
|
||||
///
|
||||
/// Note that seeding `XorShiftRng` from another `XorShiftRng` provides an
|
||||
/// extreme example of what can go wrong: the new PRNG will be a clone
|
||||
/// of the parent.
|
||||
///
|
||||
/// PRNG implementations are allowed to assume that a good RNG is provided
|
||||
/// for seeding, and that it is cryptographically secure when appropriate.
|
||||
/// As of `rand` 0.7 / `rand_core` 0.5, implementations overriding this
|
||||
/// method should ensure the implementation satisfies reproducibility
|
||||
/// (in prior versions this was not required).
|
||||
///
|
||||
/// [`rand`]: https://docs.rs/rand
|
||||
fn from_rng<R: Rng + ?Sized>(rng: &mut R) -> Self {
|
||||
let mut seed = Self::Seed::default();
|
||||
rng.fill_bytes(seed.as_mut());
|
||||
Self::from_seed(seed)
|
||||
}
|
||||
|
||||
/// Create a new PRNG seeded from a potentially fallible `Rng`.
|
||||
///
|
||||
/// See [`from_rng`][SeedableRng::from_rng] docs for more information.
|
||||
fn try_from_rng<R: TryRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
|
||||
let mut seed = Self::Seed::default();
|
||||
rng.try_fill_bytes(seed.as_mut())?;
|
||||
Ok(Self::from_seed(seed))
|
||||
}
|
||||
|
||||
/// Fork this PRNG
|
||||
///
|
||||
/// This creates a new PRNG from the current one by initializing a new one and
|
||||
/// seeding it from the current one.
|
||||
///
|
||||
/// This is useful when initializing a PRNG for a thread
|
||||
fn fork(&mut self) -> Self
|
||||
where
|
||||
Self: Rng,
|
||||
{
|
||||
Self::from_rng(self)
|
||||
}
|
||||
|
||||
/// Fork this PRNG
|
||||
///
|
||||
/// This creates a new PRNG from the current one by initializing a new one and
|
||||
/// seeding it from the current one.
|
||||
///
|
||||
/// This is useful when initializing a PRNG for a thread.
|
||||
///
|
||||
/// This is the failable equivalent to [`SeedableRng::fork`]
|
||||
fn try_fork(&mut self) -> Result<Self, Self::Error>
|
||||
where
|
||||
Self: TryRng,
|
||||
{
|
||||
Self::try_from_rng(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// PCG32 generator function
|
||||
fn pcg32(state: &mut u64) -> [u8; 4] {
|
||||
const MUL: u64 = 0x5851_F42D_4C95_7F2D;
|
||||
const INC: u64 = 0xA176_54E4_6FBE_17F3;
|
||||
|
||||
// We advance the state first (to get away from the input value,
|
||||
// in case it has low Hamming Weight).
|
||||
*state = state.wrapping_mul(MUL).wrapping_add(INC);
|
||||
let state = *state;
|
||||
|
||||
// Use PCG output function with to_le to generate x:
|
||||
let xorshifted = (((state >> 18) ^ state) >> 27) as u32;
|
||||
let rot = (state >> 59) as u32;
|
||||
let x = xorshifted.rotate_right(rot);
|
||||
x.to_le_bytes()
|
||||
}
|
||||
Vendored
+70
@@ -0,0 +1,70 @@
|
||||
use crate::{Infallible, TryCryptoRng, TryRng};
|
||||
|
||||
/// Wrapper around [`TryRng`] implementation which implements [`Rng`][crate::Rng]
|
||||
/// by panicking on potential errors.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// # use rand_core::{UnwrapErr, TryRng, Rng};
|
||||
/// fn with_try_rng<R: TryRng>(mut rng: R) {
|
||||
/// // rng does not impl Rng:
|
||||
/// let _ = rng.try_next_u32(); // okay
|
||||
/// // let _ = rng.next_u32(); // error
|
||||
///
|
||||
/// // An adapter borrowing rng:
|
||||
/// let _ = UnwrapErr(&mut rng).next_u32();
|
||||
///
|
||||
/// // An adapter moving rng:
|
||||
/// let mut rng = UnwrapErr(rng);
|
||||
/// let _ = rng.next_u32();
|
||||
/// }
|
||||
///
|
||||
/// fn call_with_unsized_try_rng<R: TryRng + ?Sized>(rng: &mut R) {
|
||||
/// // R is unsized, thus we must use &mut R:
|
||||
/// let mut rng = UnwrapErr(rng);
|
||||
/// let _ = rng.next_u32();
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
|
||||
pub struct UnwrapErr<R: TryRng>(pub R);
|
||||
|
||||
impl<R: TryRng> TryRng for UnwrapErr<R> {
|
||||
type Error = Infallible;
|
||||
|
||||
#[inline]
|
||||
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
|
||||
self.0.try_next_u32().map_err(panic_msg)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
|
||||
self.0.try_next_u64().map_err(panic_msg)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
|
||||
self.0.try_fill_bytes(dst).map_err(panic_msg)
|
||||
}
|
||||
}
|
||||
|
||||
fn panic_msg(err: impl core::error::Error) -> Infallible {
|
||||
panic!("rand_core::UnwrapErr: failed to unwrap: {err}")
|
||||
}
|
||||
|
||||
impl<R: TryCryptoRng> TryCryptoRng for UnwrapErr<R> {}
|
||||
|
||||
impl<'r, R: TryRng + ?Sized> UnwrapErr<&'r mut R> {
|
||||
/// Reborrow with a new lifetime
|
||||
///
|
||||
/// Rust allows references like `&T` or `&mut T` to be "reborrowed" through
|
||||
/// coercion: essentially, the pointer is copied under a new, shorter, lifetime.
|
||||
/// Until rfcs#1403 lands, reborrows on user types require a method call.
|
||||
#[inline(always)]
|
||||
pub fn re<'b>(&'b mut self) -> UnwrapErr<&'b mut R>
|
||||
where
|
||||
'r: 'b,
|
||||
{
|
||||
UnwrapErr(self.0)
|
||||
}
|
||||
}
|
||||
Vendored
+151
@@ -0,0 +1,151 @@
|
||||
//! Utilties to aid trait implementations
|
||||
//!
|
||||
//! ## Portability
|
||||
//!
|
||||
//! For cross-platform reproducibility, Little-Endian order (least-significant
|
||||
//! part first) has been chosen as the standard for inter-type conversion.
|
||||
//! For example, [`next_u64_via_u32`] generates two `u32` values `x, y`,
|
||||
//! then outputs `(y << 32) | x`.
|
||||
//!
|
||||
//! Byte-swapping (like the std `to_le` functions) is only needed to convert
|
||||
//! to/from byte sequences, and since its purpose is reproducibility,
|
||||
//! non-reproducible sources (e.g. `OsRng`) need not bother with it.
|
||||
//!
|
||||
//! ## Implementing [`TryRng`]
|
||||
//!
|
||||
//! Usually an implementation of [`TryRng`] will implement one of the three
|
||||
//! methods over its internal source. The following helpers are provided for
|
||||
//! the remaining implementations.
|
||||
//!
|
||||
//! **`fn try_next_u32`:**
|
||||
//! - `self.next_u64() as u32`
|
||||
//! - `(self.next_u64() >> 32) as u32`
|
||||
//! - <code>[next_word_via_fill][](self)</code>
|
||||
//!
|
||||
//! **`fn try_next_u64`:**
|
||||
//! - <code>[next_u64_via_u32][](self)</code>
|
||||
//! - <code>[next_word_via_fill][](self)</code>
|
||||
//!
|
||||
//! **`fn try_fill_bytes`:**
|
||||
//! - <code>[fill_bytes_via_next_word][](self, dest)</code>
|
||||
//!
|
||||
//! ## Implementing [`SeedableRng`]
|
||||
//!
|
||||
//! In many cases, [`SeedableRng::Seed`] must be converted to `[u32; _]` or
|
||||
//! `[u64; _]`. [`read_words`] may be used for this.
|
||||
//!
|
||||
//! [`SeedableRng`]: crate::SeedableRng
|
||||
//! [`SeedableRng::Seed`]: crate::SeedableRng::Seed
|
||||
//!
|
||||
//! ## Example
|
||||
//!
|
||||
//! We demonstrate a simple multiplicative congruential generator (MCG), taken
|
||||
//! from M.E. O'Neill's blog post [Does It Beat the Minimal Standard?][0].
|
||||
//!
|
||||
//! [0]: https://www.pcg-random.org/posts/does-it-beat-the-minimal-standard.html
|
||||
//!
|
||||
//! ```
|
||||
//! use core::convert::Infallible;
|
||||
//! use rand_core::{Rng, SeedableRng, TryRng, utils};
|
||||
//!
|
||||
//! pub struct Mcg128(u128);
|
||||
//!
|
||||
//! impl SeedableRng for Mcg128 {
|
||||
//! type Seed = [u8; 16];
|
||||
//!
|
||||
//! #[inline]
|
||||
//! fn from_seed(seed: Self::Seed) -> Self {
|
||||
//! // Always use little-endian byte order to ensure portable results
|
||||
//! Self(u128::from_le_bytes(seed))
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! impl TryRng for Mcg128 {
|
||||
//! type Error = Infallible;
|
||||
//!
|
||||
//! #[inline]
|
||||
//! fn try_next_u32(&mut self) -> Result<u32, Infallible> {
|
||||
//! Ok((self.next_u64() >> 32) as u32)
|
||||
//! }
|
||||
//!
|
||||
//! #[inline]
|
||||
//! fn try_next_u64(&mut self) -> Result<u64, Infallible> {
|
||||
//! self.0 = self.0.wrapping_mul(0x0fc94e3bf4e9ab32866458cd56f5e605);
|
||||
//! Ok((self.0 >> 64) as u64)
|
||||
//! }
|
||||
//!
|
||||
//! #[inline]
|
||||
//! fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Infallible> {
|
||||
//! utils::fill_bytes_via_next_word(dst, || self.try_next_u64())
|
||||
//! }
|
||||
//! }
|
||||
//! #
|
||||
//! # let mut rng = Mcg128::seed_from_u64(42);
|
||||
//! # assert_eq!(rng.next_u32(), 3443086493);
|
||||
//! # assert_eq!(rng.next_u64(), 3462997187007721903);
|
||||
//! # let mut buf = [0u8; 5];
|
||||
//! # rng.fill_bytes(&mut buf);
|
||||
//! # assert_eq!(buf, [154, 23, 43, 68, 75]);
|
||||
//! ```
|
||||
|
||||
use crate::TryRng;
|
||||
pub use crate::word::Word;
|
||||
|
||||
/// Generate a `u64` using `next_u32`, little-endian order.
|
||||
#[inline]
|
||||
pub fn next_u64_via_u32<R: TryRng + ?Sized>(rng: &mut R) -> Result<u64, R::Error> {
|
||||
// Use LE; we explicitly generate one value before the next.
|
||||
let x = u64::from(rng.try_next_u32()?);
|
||||
let y = u64::from(rng.try_next_u32()?);
|
||||
Ok((y << 32) | x)
|
||||
}
|
||||
|
||||
/// Fill `dst` with bytes using `next_word`
|
||||
///
|
||||
/// This may be used to implement `fill_bytes` over `next_u32` or
|
||||
/// `next_u64`. Words are used in order of generation. The last word may be
|
||||
/// partially discarded.
|
||||
#[inline]
|
||||
pub fn fill_bytes_via_next_word<E, W: Word>(
|
||||
dst: &mut [u8],
|
||||
mut next_word: impl FnMut() -> Result<W, E>,
|
||||
) -> Result<(), E> {
|
||||
let mut chunks = dst.chunks_exact_mut(size_of::<W>());
|
||||
for chunk in &mut chunks {
|
||||
let val = next_word()?;
|
||||
chunk.copy_from_slice(val.to_le_bytes().as_ref());
|
||||
}
|
||||
let rem = chunks.into_remainder();
|
||||
if !rem.is_empty() {
|
||||
let val = next_word()?.to_le_bytes();
|
||||
rem.copy_from_slice(&val.as_ref()[..rem.len()]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate a `u32` or `u64` word using `fill_bytes`
|
||||
pub fn next_word_via_fill<W: Word, R: TryRng>(rng: &mut R) -> Result<W, R::Error> {
|
||||
let mut buf: W::Bytes = Default::default();
|
||||
rng.try_fill_bytes(buf.as_mut())?;
|
||||
Ok(W::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Reads an array of words from a byte slice
|
||||
///
|
||||
/// Words are read from `src` in order, using LE conversion from bytes.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `size_of_val(src) != size_of::<[W; N]>()`.
|
||||
#[inline(always)]
|
||||
pub fn read_words<W: Word, const N: usize>(src: &[u8]) -> [W; N] {
|
||||
assert_eq!(size_of_val(src), size_of::<[W; N]>());
|
||||
let mut dst = [W::from_usize(0); N];
|
||||
let chunks = src.chunks_exact(size_of::<W>());
|
||||
for (out, chunk) in dst.iter_mut().zip(chunks) {
|
||||
let mut buf: W::Bytes = Default::default();
|
||||
buf.as_mut().copy_from_slice(chunk);
|
||||
*out = W::from_le_bytes(buf);
|
||||
}
|
||||
dst
|
||||
}
|
||||
Vendored
+66
@@ -0,0 +1,66 @@
|
||||
//! The [`Word`] trait
|
||||
|
||||
/// A marker trait for supported "word" types.
|
||||
///
|
||||
/// This is implemented for: `u32`, `u64`.
|
||||
pub trait Word: sealed::Sealed {}
|
||||
|
||||
impl Word for u32 {}
|
||||
impl Word for u64 {}
|
||||
|
||||
mod sealed {
|
||||
/// Sealed trait implemented for `u32` and `u64`.
|
||||
pub trait Sealed: Default + Copy + TryFrom<usize> + Eq + core::hash::Hash {
|
||||
type Bytes: Default + Sized + AsRef<[u8]> + AsMut<[u8]>;
|
||||
|
||||
fn from_le_bytes(bytes: Self::Bytes) -> Self;
|
||||
fn to_le_bytes(self) -> Self::Bytes;
|
||||
|
||||
fn from_usize(val: usize) -> Self;
|
||||
fn into_usize(self) -> usize;
|
||||
}
|
||||
|
||||
impl Sealed for u32 {
|
||||
type Bytes = [u8; 4];
|
||||
|
||||
#[inline(always)]
|
||||
fn from_le_bytes(bytes: Self::Bytes) -> Self {
|
||||
Self::from_le_bytes(bytes)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_le_bytes(self) -> Self::Bytes {
|
||||
Self::to_le_bytes(self)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn from_usize(val: usize) -> Self {
|
||||
val.try_into().unwrap()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn into_usize(self) -> usize {
|
||||
self.try_into().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Sealed for u64 {
|
||||
type Bytes = [u8; 8];
|
||||
|
||||
#[inline(always)]
|
||||
fn from_le_bytes(bytes: Self::Bytes) -> Self {
|
||||
Self::from_le_bytes(bytes)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_le_bytes(self) -> Self::Bytes {
|
||||
Self::to_le_bytes(self)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn from_usize(val: usize) -> Self {
|
||||
val.try_into().unwrap()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn into_usize(self) -> usize {
|
||||
self.try_into().unwrap()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user