chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

534
vendor/rand_core/src/block.rs vendored Normal file
View File

@@ -0,0 +1,534 @@
// Copyright 2018 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The `BlockRngCore` trait and implementation helpers
//!
//! The [`BlockRngCore`] trait exists to assist in the implementation of RNGs
//! which generate a block of data in a cache instead of returning generated
//! values directly.
//!
//! Usage of this trait is optional, but provides two advantages:
//! implementations only need to concern themselves with generation of the
//! block, not the various [`RngCore`] methods (especially [`fill_bytes`], where
//! the optimal implementations are not trivial), and this allows
//! `ReseedingRng` (see [`rand`](https://docs.rs/rand) crate) perform periodic
//! reseeding with very low overhead.
//!
//! # Example
//!
//! ```no_run
//! use rand_core::{RngCore, SeedableRng};
//! use rand_core::block::{BlockRngCore, BlockRng};
//!
//! struct MyRngCore;
//!
//! impl BlockRngCore for MyRngCore {
//! type Item = u32;
//! type Results = [u32; 16];
//!
//! fn generate(&mut self, results: &mut Self::Results) {
//! unimplemented!()
//! }
//! }
//!
//! impl SeedableRng for MyRngCore {
//! type Seed = [u8; 32];
//! fn from_seed(seed: Self::Seed) -> Self {
//! unimplemented!()
//! }
//! }
//!
//! // optionally, also implement CryptoBlockRng for MyRngCore
//!
//! // Final RNG.
//! let mut rng = BlockRng::<MyRngCore>::seed_from_u64(0);
//! println!("First value: {}", rng.next_u32());
//! ```
//!
//! [`BlockRngCore`]: crate::block::BlockRngCore
//! [`fill_bytes`]: RngCore::fill_bytes
use crate::impls::fill_via_chunks;
use crate::{CryptoRng, RngCore, SeedableRng, TryRngCore};
use core::fmt;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// A trait for RNGs which do not generate random numbers individually, but in
/// blocks (typically `[u32; N]`). This technique is commonly used by
/// cryptographic RNGs to improve performance.
///
/// See the [module][crate::block] documentation for details.
pub trait BlockRngCore {
/// Results element type, e.g. `u32`.
type Item;
/// Results type. This is the 'block' an RNG implementing `BlockRngCore`
/// generates, which will usually be an array like `[u32; 16]`.
type Results: AsRef<[Self::Item]> + AsMut<[Self::Item]> + Default;
/// Generate a new block of results.
fn generate(&mut self, results: &mut Self::Results);
}
/// A marker trait used to indicate that an [`RngCore`] implementation is
/// supposed to be cryptographically secure.
///
/// See [`CryptoRng`] docs for more information.
pub trait CryptoBlockRng: BlockRngCore {}
/// A wrapper type implementing [`RngCore`] for some type implementing
/// [`BlockRngCore`] with `u32` array buffer; i.e. this can be used to implement
/// a full RNG from just a `generate` function.
///
/// The `core` field may be accessed directly but the results buffer may not.
/// PRNG implementations can simply use a type alias
/// (`pub type MyRng = BlockRng<MyRngCore>;`) but might prefer to use a
/// wrapper type (`pub struct MyRng(BlockRng<MyRngCore>);`); the latter must
/// re-implement `RngCore` but hides the implementation details and allows
/// extra functionality to be defined on the RNG
/// (e.g. `impl MyRng { fn set_stream(...){...} }`).
///
/// `BlockRng` has heavily optimized implementations of the [`RngCore`] methods
/// reading values from the results buffer, as well as
/// calling [`BlockRngCore::generate`] directly on the output array when
/// [`fill_bytes`] is called on a large array. These methods also handle
/// the bookkeeping of when to generate a new batch of values.
///
/// No whole generated `u32` values are thrown away and all values are consumed
/// in-order. [`next_u32`] simply takes the next available `u32` value.
/// [`next_u64`] is implemented by combining two `u32` values, least
/// significant first. [`fill_bytes`] consume a whole number of `u32` values,
/// converting each `u32` to a byte slice in little-endian order. If the requested byte
/// length is not a multiple of 4, some bytes will be discarded.
///
/// See also [`BlockRng64`] which uses `u64` array buffers. Currently there is
/// no direct support for other buffer types.
///
/// For easy initialization `BlockRng` also implements [`SeedableRng`].
///
/// [`next_u32`]: RngCore::next_u32
/// [`next_u64`]: RngCore::next_u64
/// [`fill_bytes`]: RngCore::fill_bytes
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde",
serde(
bound = "for<'x> R: Serialize + Deserialize<'x>, for<'x> R::Results: Serialize + Deserialize<'x>"
)
)]
pub struct BlockRng<R: BlockRngCore> {
results: R::Results,
index: usize,
/// The *core* part of the RNG, implementing the `generate` function.
pub core: R,
}
// Custom Debug implementation that does not expose the contents of `results`.
impl<R: BlockRngCore + fmt::Debug> fmt::Debug for BlockRng<R> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("BlockRng")
.field("core", &self.core)
.field("result_len", &self.results.as_ref().len())
.field("index", &self.index)
.finish()
}
}
impl<R: BlockRngCore> BlockRng<R> {
/// Create a new `BlockRng` from an existing RNG implementing
/// `BlockRngCore`. Results will be generated on first use.
#[inline]
pub fn new(core: R) -> BlockRng<R> {
let results_empty = R::Results::default();
BlockRng {
core,
index: results_empty.as_ref().len(),
results: results_empty,
}
}
/// 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)]
pub fn index(&self) -> usize {
self.index
}
/// Reset the number of available results.
/// This will force a new set of results to be generated on next use.
#[inline]
pub fn reset(&mut self) {
self.index = self.results.as_ref().len();
}
/// Generate a new set of results immediately, setting the index to the
/// given value.
#[inline]
pub fn generate_and_set(&mut self, index: usize) {
assert!(index < self.results.as_ref().len());
self.core.generate(&mut self.results);
self.index = index;
}
}
impl<R: BlockRngCore<Item = u32>> RngCore for BlockRng<R> {
#[inline]
fn next_u32(&mut self) -> u32 {
if self.index >= self.results.as_ref().len() {
self.generate_and_set(0);
}
let value = self.results.as_ref()[self.index];
self.index += 1;
value
}
#[inline]
fn next_u64(&mut self) -> u64 {
let read_u64 = |results: &[u32], index| {
let data = &results[index..=index + 1];
(u64::from(data[1]) << 32) | u64::from(data[0])
};
let len = self.results.as_ref().len();
let index = self.index;
if index < len - 1 {
self.index += 2;
// Read an u64 from the current index
read_u64(self.results.as_ref(), index)
} else if index >= len {
self.generate_and_set(2);
read_u64(self.results.as_ref(), 0)
} else {
let x = u64::from(self.results.as_ref()[len - 1]);
self.generate_and_set(1);
let y = u64::from(self.results.as_ref()[0]);
(y << 32) | x
}
}
#[inline]
fn fill_bytes(&mut self, dest: &mut [u8]) {
let mut read_len = 0;
while read_len < dest.len() {
if self.index >= self.results.as_ref().len() {
self.generate_and_set(0);
}
let (consumed_u32, filled_u8) =
fill_via_chunks(&self.results.as_mut()[self.index..], &mut dest[read_len..]);
self.index += consumed_u32;
read_len += filled_u8;
}
}
}
impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng<R> {
type Seed = R::Seed;
#[inline(always)]
fn from_seed(seed: Self::Seed) -> Self {
Self::new(R::from_seed(seed))
}
#[inline(always)]
fn seed_from_u64(seed: u64) -> Self {
Self::new(R::seed_from_u64(seed))
}
#[inline(always)]
fn from_rng(rng: &mut impl RngCore) -> Self {
Self::new(R::from_rng(rng))
}
#[inline(always)]
fn try_from_rng<S: TryRngCore>(rng: &mut S) -> Result<Self, S::Error> {
R::try_from_rng(rng).map(Self::new)
}
}
impl<R: CryptoBlockRng + BlockRngCore<Item = u32>> CryptoRng for BlockRng<R> {}
/// A wrapper type implementing [`RngCore`] for some type implementing
/// [`BlockRngCore`] with `u64` array buffer; i.e. this can be used to implement
/// a full RNG from just a `generate` function.
///
/// This is similar to [`BlockRng`], but specialized for algorithms that operate
/// on `u64` values.
///
/// No whole generated `u64` values are thrown away and all values are consumed
/// in-order. [`next_u64`] simply takes the next available `u64` value.
/// [`next_u32`] is however a bit special: half of a `u64` is consumed, leaving
/// the other half in the buffer. If the next function called is [`next_u32`]
/// then the other half is then consumed, however both [`next_u64`] and
/// [`fill_bytes`] discard the rest of any half-consumed `u64`s when called.
///
/// [`fill_bytes`] consumes a whole number of `u64` values. If the requested length
/// is not a multiple of 8, some bytes will be discarded.
///
/// [`next_u32`]: RngCore::next_u32
/// [`next_u64`]: RngCore::next_u64
/// [`fill_bytes`]: RngCore::fill_bytes
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BlockRng64<R: BlockRngCore + ?Sized> {
results: R::Results,
index: usize,
half_used: bool, // true if only half of the previous result is used
/// The *core* part of the RNG, implementing the `generate` function.
pub core: R,
}
// Custom Debug implementation that does not expose the contents of `results`.
impl<R: BlockRngCore + fmt::Debug> fmt::Debug for BlockRng64<R> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("BlockRng64")
.field("core", &self.core)
.field("result_len", &self.results.as_ref().len())
.field("index", &self.index)
.field("half_used", &self.half_used)
.finish()
}
}
impl<R: BlockRngCore> BlockRng64<R> {
/// Create a new `BlockRng` from an existing RNG implementing
/// `BlockRngCore`. Results will be generated on first use.
#[inline]
pub fn new(core: R) -> BlockRng64<R> {
let results_empty = R::Results::default();
BlockRng64 {
core,
index: results_empty.as_ref().len(),
half_used: false,
results: results_empty,
}
}
/// 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)]
pub fn index(&self) -> usize {
self.index
}
/// Reset the number of available results.
/// This will force a new set of results to be generated on next use.
#[inline]
pub fn reset(&mut self) {
self.index = self.results.as_ref().len();
self.half_used = false;
}
/// Generate a new set of results immediately, setting the index to the
/// given value.
#[inline]
pub fn generate_and_set(&mut self, index: usize) {
assert!(index < self.results.as_ref().len());
self.core.generate(&mut self.results);
self.index = index;
self.half_used = false;
}
}
impl<R: BlockRngCore<Item = u64>> RngCore for BlockRng64<R> {
#[inline]
fn next_u32(&mut self) -> u32 {
let mut index = self.index - self.half_used as usize;
if index >= self.results.as_ref().len() {
self.core.generate(&mut self.results);
self.index = 0;
index = 0;
// `self.half_used` is by definition `false`
self.half_used = false;
}
let shift = 32 * (self.half_used as usize);
self.half_used = !self.half_used;
self.index += self.half_used as usize;
(self.results.as_ref()[index] >> shift) as u32
}
#[inline]
fn next_u64(&mut self) -> u64 {
if self.index >= self.results.as_ref().len() {
self.core.generate(&mut self.results);
self.index = 0;
}
let value = self.results.as_ref()[self.index];
self.index += 1;
self.half_used = false;
value
}
#[inline]
fn fill_bytes(&mut self, dest: &mut [u8]) {
let mut read_len = 0;
self.half_used = false;
while read_len < dest.len() {
if self.index >= self.results.as_ref().len() {
self.core.generate(&mut self.results);
self.index = 0;
}
let (consumed_u64, filled_u8) =
fill_via_chunks(&self.results.as_mut()[self.index..], &mut dest[read_len..]);
self.index += consumed_u64;
read_len += filled_u8;
}
}
}
impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng64<R> {
type Seed = R::Seed;
#[inline(always)]
fn from_seed(seed: Self::Seed) -> Self {
Self::new(R::from_seed(seed))
}
#[inline(always)]
fn seed_from_u64(seed: u64) -> Self {
Self::new(R::seed_from_u64(seed))
}
#[inline(always)]
fn from_rng(rng: &mut impl RngCore) -> Self {
Self::new(R::from_rng(rng))
}
#[inline(always)]
fn try_from_rng<S: TryRngCore>(rng: &mut S) -> Result<Self, S::Error> {
R::try_from_rng(rng).map(Self::new)
}
}
impl<R: CryptoBlockRng + BlockRngCore<Item = u64>> CryptoRng for BlockRng64<R> {}
#[cfg(test)]
mod test {
use crate::block::{BlockRng, BlockRng64, BlockRngCore};
use crate::{RngCore, SeedableRng};
#[derive(Debug, Clone)]
struct DummyRng {
counter: u32,
}
impl BlockRngCore for DummyRng {
type Item = u32;
type Results = [u32; 16];
fn generate(&mut self, results: &mut Self::Results) {
for r in results {
*r = self.counter;
self.counter = self.counter.wrapping_add(3511615421);
}
}
}
impl SeedableRng for DummyRng {
type Seed = [u8; 4];
fn from_seed(seed: Self::Seed) -> Self {
DummyRng {
counter: u32::from_le_bytes(seed),
}
}
}
#[test]
fn blockrng_next_u32_vs_next_u64() {
let mut rng1 = BlockRng::<DummyRng>::from_seed([1, 2, 3, 4]);
let mut rng2 = rng1.clone();
let mut rng3 = rng1.clone();
let mut a = [0; 16];
a[..4].copy_from_slice(&rng1.next_u32().to_le_bytes());
a[4..12].copy_from_slice(&rng1.next_u64().to_le_bytes());
a[12..].copy_from_slice(&rng1.next_u32().to_le_bytes());
let mut b = [0; 16];
b[..4].copy_from_slice(&rng2.next_u32().to_le_bytes());
b[4..8].copy_from_slice(&rng2.next_u32().to_le_bytes());
b[8..].copy_from_slice(&rng2.next_u64().to_le_bytes());
assert_eq!(a, b);
let mut c = [0; 16];
c[..8].copy_from_slice(&rng3.next_u64().to_le_bytes());
c[8..12].copy_from_slice(&rng3.next_u32().to_le_bytes());
c[12..].copy_from_slice(&rng3.next_u32().to_le_bytes());
assert_eq!(a, c);
}
#[derive(Debug, Clone)]
struct DummyRng64 {
counter: u64,
}
impl BlockRngCore for DummyRng64 {
type Item = u64;
type Results = [u64; 8];
fn generate(&mut self, results: &mut Self::Results) {
for r in results {
*r = self.counter;
self.counter = self.counter.wrapping_add(2781463553396133981);
}
}
}
impl SeedableRng for DummyRng64 {
type Seed = [u8; 8];
fn from_seed(seed: Self::Seed) -> Self {
DummyRng64 {
counter: u64::from_le_bytes(seed),
}
}
}
#[test]
fn blockrng64_next_u32_vs_next_u64() {
let mut rng1 = BlockRng64::<DummyRng64>::from_seed([1, 2, 3, 4, 5, 6, 7, 8]);
let mut rng2 = rng1.clone();
let mut rng3 = rng1.clone();
let mut a = [0; 16];
a[..4].copy_from_slice(&rng1.next_u32().to_le_bytes());
a[4..12].copy_from_slice(&rng1.next_u64().to_le_bytes());
a[12..].copy_from_slice(&rng1.next_u32().to_le_bytes());
let mut b = [0; 16];
b[..4].copy_from_slice(&rng2.next_u32().to_le_bytes());
b[4..8].copy_from_slice(&rng2.next_u32().to_le_bytes());
b[8..].copy_from_slice(&rng2.next_u64().to_le_bytes());
assert_ne!(a, b);
assert_eq!(&a[..4], &b[..4]);
assert_eq!(&a[4..12], &b[8..]);
let mut c = [0; 16];
c[..8].copy_from_slice(&rng3.next_u64().to_le_bytes());
c[8..12].copy_from_slice(&rng3.next_u32().to_le_bytes());
c[12..].copy_from_slice(&rng3.next_u32().to_le_bytes());
assert_eq!(b, c);
}
}

217
vendor/rand_core/src/impls.rs vendored Normal file
View File

@@ -0,0 +1,217 @@
// Copyright 2018 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Helper functions for implementing `RngCore` functions.
//!
//! For cross-platform reproducibility, these functions all use Little Endian:
//! least-significant part first. For example, `next_u64_via_u32` takes `u32`
//! values `x, y`, then outputs `(y << 32) | x`. To implement `next_u32`
//! from `next_u64` in little-endian order, one should use `next_u64() as u32`.
//!
//! 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.
use crate::RngCore;
/// Implement `next_u64` via `next_u32`, little-endian order.
pub fn next_u64_via_u32<R: RngCore + ?Sized>(rng: &mut R) -> u64 {
// Use LE; we explicitly generate one value before the next.
let x = u64::from(rng.next_u32());
let y = u64::from(rng.next_u32());
(y << 32) | x
}
/// Implement `fill_bytes` via `next_u64` and `next_u32`, little-endian order.
///
/// The fastest way to fill a slice is usually to work as long as possible with
/// integers. That is why this method mostly uses `next_u64`, and only when
/// there are 4 or less bytes remaining at the end of the slice it uses
/// `next_u32` once.
pub fn fill_bytes_via_next<R: RngCore + ?Sized>(rng: &mut R, dest: &mut [u8]) {
let mut left = dest;
while left.len() >= 8 {
let (l, r) = { left }.split_at_mut(8);
left = r;
let chunk: [u8; 8] = rng.next_u64().to_le_bytes();
l.copy_from_slice(&chunk);
}
let n = left.len();
if n > 4 {
let chunk: [u8; 8] = rng.next_u64().to_le_bytes();
left.copy_from_slice(&chunk[..n]);
} else if n > 0 {
let chunk: [u8; 4] = rng.next_u32().to_le_bytes();
left.copy_from_slice(&chunk[..n]);
}
}
pub(crate) trait Observable: Copy {
type Bytes: Sized + AsRef<[u8]>;
fn to_le_bytes(self) -> Self::Bytes;
}
impl Observable for u32 {
type Bytes = [u8; 4];
fn to_le_bytes(self) -> Self::Bytes {
Self::to_le_bytes(self)
}
}
impl Observable for u64 {
type Bytes = [u8; 8];
fn to_le_bytes(self) -> Self::Bytes {
Self::to_le_bytes(self)
}
}
/// Fill dest from src
///
/// Returns `(n, byte_len)`. `src[..n]` is consumed,
/// `dest[..byte_len]` is filled. `src[n..]` and `dest[byte_len..]` are left
/// unaltered.
pub(crate) fn fill_via_chunks<T: Observable>(src: &[T], dest: &mut [u8]) -> (usize, usize) {
let size = core::mem::size_of::<T>();
// Always use little endian for portability of results.
let mut dest = dest.chunks_exact_mut(size);
let mut src = src.iter();
let zipped = dest.by_ref().zip(src.by_ref());
let num_chunks = zipped.len();
zipped.for_each(|(dest, src)| dest.copy_from_slice(src.to_le_bytes().as_ref()));
let byte_len = num_chunks * size;
if let Some(src) = src.next() {
// We have consumed all full chunks of dest, but not src.
let dest = dest.into_remainder();
let n = dest.len();
if n > 0 {
dest.copy_from_slice(&src.to_le_bytes().as_ref()[..n]);
return (num_chunks + 1, byte_len + n);
}
}
(num_chunks, byte_len)
}
/// Implement `fill_bytes` by reading chunks from the output buffer of a block
/// based RNG.
///
/// The return values are `(consumed_u32, filled_u8)`.
///
/// `src` is not modified; it is taken as a `&mut` reference for backward
/// compatibility with previous versions that did change it.
///
/// `filled_u8` is the number of filled bytes in `dest`, which may be less than
/// the length of `dest`.
/// `consumed_u32` is the number of words consumed from `src`, which is the same
/// as `filled_u8 / 4` rounded up.
///
/// # Example
/// (from `IsaacRng`)
///
/// ```ignore
/// fn fill_bytes(&mut self, dest: &mut [u8]) {
/// let mut read_len = 0;
/// while read_len < dest.len() {
/// if self.index >= self.rsl.len() {
/// self.isaac();
/// }
///
/// let (consumed_u32, filled_u8) =
/// impls::fill_via_u32_chunks(&mut self.rsl[self.index..],
/// &mut dest[read_len..]);
///
/// self.index += consumed_u32;
/// read_len += filled_u8;
/// }
/// }
/// ```
#[deprecated(since = "0.9.3", note = "use BlockRng instead")]
pub fn fill_via_u32_chunks(src: &mut [u32], dest: &mut [u8]) -> (usize, usize) {
fill_via_chunks(src, dest)
}
/// Implement `fill_bytes` by reading chunks from the output buffer of a block
/// based RNG.
///
/// The return values are `(consumed_u64, filled_u8)`.
///
/// `src` is not modified; it is taken as a `&mut` reference for backward
/// compatibility with previous versions that did change it.
///
/// `filled_u8` is the number of filled bytes in `dest`, which may be less than
/// the length of `dest`.
/// `consumed_u64` is the number of words consumed from `src`, which is the same
/// as `filled_u8 / 8` rounded up.
///
/// See `fill_via_u32_chunks` for an example.
#[deprecated(since = "0.9.3", note = "use BlockRng64 instead")]
pub fn fill_via_u64_chunks(src: &mut [u64], dest: &mut [u8]) -> (usize, usize) {
fill_via_chunks(src, dest)
}
/// Implement `next_u32` via `fill_bytes`, little-endian order.
pub fn next_u32_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u32 {
let mut buf = [0; 4];
rng.fill_bytes(&mut buf);
u32::from_le_bytes(buf)
}
/// Implement `next_u64` via `fill_bytes`, little-endian order.
pub fn next_u64_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u64 {
let mut buf = [0; 8];
rng.fill_bytes(&mut buf);
u64::from_le_bytes(buf)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_fill_via_u32_chunks() {
let src_orig = [1u32, 2, 3];
let mut src = src_orig;
let mut dst = [0u8; 11];
assert_eq!(fill_via_chunks(&mut src, &mut dst), (3, 11));
assert_eq!(dst, [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0]);
let mut src = src_orig;
let mut dst = [0u8; 13];
assert_eq!(fill_via_chunks(&mut src, &mut dst), (3, 12));
assert_eq!(dst, [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0]);
let mut src = src_orig;
let mut dst = [0u8; 5];
assert_eq!(fill_via_chunks(&mut src, &mut dst), (2, 5));
assert_eq!(dst, [1, 0, 0, 0, 2]);
}
#[test]
fn test_fill_via_u64_chunks() {
let src_orig = [1u64, 2];
let mut src = src_orig;
let mut dst = [0u8; 11];
assert_eq!(fill_via_chunks(&mut src, &mut dst), (2, 11));
assert_eq!(dst, [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0]);
let mut src = src_orig;
let mut dst = [0u8; 17];
assert_eq!(fill_via_chunks(&mut src, &mut dst), (2, 16));
assert_eq!(dst, [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0]);
let mut src = src_orig;
let mut dst = [0u8; 5];
assert_eq!(fill_via_chunks(&mut src, &mut dst), (1, 5));
assert_eq!(dst, [1, 0, 0, 0, 0]);
}
}

64
vendor/rand_core/src/le.rs vendored Normal file
View File

@@ -0,0 +1,64 @@
// Copyright 2018 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Little-Endian utilities
//!
//! Little-Endian order has been chosen for internal usage; this makes some
//! useful functions available.
/// Reads unsigned 32 bit integers from `src` into `dst`.
///
/// # Panics
///
/// If `dst` has insufficient space (`4*dst.len() < src.len()`).
#[inline]
#[track_caller]
pub fn read_u32_into(src: &[u8], dst: &mut [u32]) {
assert!(src.len() >= 4 * dst.len());
for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(4)) {
*out = u32::from_le_bytes(chunk.try_into().unwrap());
}
}
/// Reads unsigned 64 bit integers from `src` into `dst`.
///
/// # Panics
///
/// If `dst` has insufficient space (`8*dst.len() < src.len()`).
#[inline]
#[track_caller]
pub fn read_u64_into(src: &[u8], dst: &mut [u64]) {
assert!(src.len() >= 8 * dst.len());
for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(8)) {
*out = u64::from_le_bytes(chunk.try_into().unwrap());
}
}
#[test]
fn test_read() {
let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let mut buf = [0u32; 4];
read_u32_into(&bytes, &mut buf);
assert_eq!(buf[0], 0x04030201);
assert_eq!(buf[3], 0x100F0E0D);
let mut buf = [0u32; 3];
read_u32_into(&bytes[1..13], &mut buf); // unaligned
assert_eq!(buf[0], 0x05040302);
assert_eq!(buf[2], 0x0D0C0B0A);
let mut buf = [0u64; 2];
read_u64_into(&bytes, &mut buf);
assert_eq!(buf[0], 0x0807060504030201);
assert_eq!(buf[1], 0x100F0E0D0C0B0A09);
let mut buf = [0u64; 1];
read_u64_into(&bytes[7..15], &mut buf); // unaligned
assert_eq!(buf[0], 0x0F0E0D0C0B0A0908);
}

771
vendor/rand_core/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,771 @@
// Copyright 2018 Developers of the Rand project.
// Copyright 2017-2018 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Random number generation traits
//!
//! This crate is mainly of interest to crates publishing implementations of
//! [`RngCore`]. Other users are encouraged to use the [`rand`] crate instead
//! which re-exports the main traits and error types.
//!
//! [`RngCore`] is the core trait implemented by algorithmic pseudo-random number
//! generators and external random-number sources.
//!
//! [`SeedableRng`] is an extension trait for construction from fixed seeds and
//! other random number generators.
//!
//! The [`impls`] and [`le`] sub-modules include a few small functions to assist
//! implementation of [`RngCore`].
//!
//! [`rand`]: https://docs.rs/rand
#![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",
html_root_url = "https://rust-random.github.io/rand/"
)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![doc(test(attr(allow(unused_variables), deny(warnings))))]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![no_std]
#[cfg(feature = "std")]
extern crate std;
use core::{fmt, ops::DerefMut};
pub mod block;
pub mod impls;
pub mod le;
#[cfg(feature = "os_rng")]
mod os;
#[cfg(feature = "os_rng")]
pub use os::{OsError, OsRng};
/// Implementation-level interface for RNGs
///
/// This trait encapsulates the low-level functionality common to all
/// generators, and is the "back end", to be implemented by generators.
/// End users should normally use the [`rand::Rng`] trait
/// which is automatically implemented for every type implementing `RngCore`.
///
/// Three different methods for generating random data are provided since the
/// optimal implementation of each is dependent on the type of generator. There
/// is no required relationship between the output of each; e.g. many
/// implementations of [`fill_bytes`] consume a whole number of `u32` or `u64`
/// values and drop any remaining unused bytes. The same can happen with the
/// [`next_u32`] and [`next_u64`] methods, implementations may discard some
/// random bits for efficiency.
///
/// Implementers should produce bits uniformly. Pathological RNGs (e.g. always
/// returning the same value, or never setting certain bits) can break rejection
/// sampling used by random distributions, and also break other RNGs when
/// seeding them via [`SeedableRng::from_rng`].
///
/// 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).
///
/// Typically an RNG will implement only one of the methods available
/// in this trait directly, then use the helper functions from the
/// [`impls`] module to implement the other methods.
///
/// Note that implementors of [`RngCore`] also automatically implement
/// the [`TryRngCore`] trait with the `Error` associated type being
/// equal to [`Infallible`].
///
/// It is recommended that implementations also implement:
///
/// - `Debug` with a custom implementation which *does not* print any internal
/// state (at least, [`CryptoRng`]s should not risk leaking state through
/// `Debug`).
/// - `Serialize` and `Deserialize` (from Serde), preferably making Serde
/// support optional at the crate level in PRNG libs.
/// - `Clone`, if possible.
/// - *never* implement `Copy` (accidental copies may cause repeated values).
/// - *do not* implement `Default` for pseudorandom generators, but instead
/// implement [`SeedableRng`], to guide users towards proper seeding.
/// External / hardware RNGs can choose to implement `Default`.
/// - `Eq` and `PartialEq` could be implemented, but are probably not useful.
///
/// # Example
///
/// A simple example, obviously not generating very *random* output:
///
/// ```
/// #![allow(dead_code)]
/// use rand_core::{RngCore, impls};
///
/// struct CountingRng(u64);
///
/// impl RngCore for CountingRng {
/// fn next_u32(&mut self) -> u32 {
/// self.next_u64() as u32
/// }
///
/// fn next_u64(&mut self) -> u64 {
/// self.0 += 1;
/// self.0
/// }
///
/// fn fill_bytes(&mut self, dst: &mut [u8]) {
/// impls::fill_bytes_via_next(self, dst)
/// }
/// }
/// ```
///
/// [`rand::Rng`]: https://docs.rs/rand/latest/rand/trait.Rng.html
/// [`fill_bytes`]: RngCore::fill_bytes
/// [`next_u32`]: RngCore::next_u32
/// [`next_u64`]: RngCore::next_u64
/// [`Infallible`]: core::convert::Infallible
pub trait RngCore {
/// Return the next random `u32`.
///
/// RNGs must implement at least one method from this trait directly. In
/// the case this method is not implemented directly, it can be implemented
/// using `self.next_u64() as u32` or via [`impls::next_u32_via_fill`].
fn next_u32(&mut self) -> u32;
/// Return the next random `u64`.
///
/// RNGs must implement at least one method from this trait directly. In
/// the case this method is not implemented directly, it can be implemented
/// via [`impls::next_u64_via_u32`] or via [`impls::next_u64_via_fill`].
fn next_u64(&mut self) -> u64;
/// Fill `dest` with random data.
///
/// RNGs must implement at least one method from this trait directly. In
/// the case this method is not implemented directly, it can be implemented
/// via [`impls::fill_bytes_via_next`].
///
/// 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<T: DerefMut> RngCore for T
where
T::Target: RngCore,
{
#[inline]
fn next_u32(&mut self) -> u32 {
self.deref_mut().next_u32()
}
#[inline]
fn next_u64(&mut self) -> u64 {
self.deref_mut().next_u64()
}
#[inline]
fn fill_bytes(&mut self, dst: &mut [u8]) {
self.deref_mut().fill_bytes(dst);
}
}
/// A marker trait over [`RngCore`] 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.
///
/// Implementors of `CryptoRng` automatically implement the [`TryCryptoRng`]
/// trait.
///
/// Implementors of `CryptoRng` should only implement [`Default`] if the
/// `default()` instances are themselves secure generators: for example if the
/// implementing type is a stateless interface over a secure external generator
/// (like [`OsRng`]) or if the `default()` instance uses a strong, fresh seed.
///
/// 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`.
pub trait CryptoRng: RngCore {}
impl<T: DerefMut> CryptoRng for T where T::Target: CryptoRng {}
/// A potentially fallible variant of [`RngCore`]
///
/// This trait is a generalization of [`RngCore`] to support potentially-
/// fallible IO-based generators such as [`OsRng`].
///
/// All implementations of [`RngCore`] automatically support this `TryRngCore`
/// trait, using [`Infallible`][core::convert::Infallible] as the associated
/// `Error` type.
///
/// An implementation of this trait may be made compatible with code requiring
/// an [`RngCore`] through [`TryRngCore::unwrap_err`]. The resulting RNG will
/// panic in case the underlying fallible RNG yields an error.
pub trait TryRngCore {
/// The type returned in the event of a RNG error.
type Error: fmt::Debug + fmt::Display;
/// 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 `dest` entirely with random data.
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error>;
/// Wrap RNG with the [`UnwrapErr`] wrapper.
fn unwrap_err(self) -> UnwrapErr<Self>
where
Self: Sized,
{
UnwrapErr(self)
}
/// Wrap RNG with the [`UnwrapMut`] wrapper.
fn unwrap_mut(&mut self) -> UnwrapMut<'_, Self> {
UnwrapMut(self)
}
/// Convert an [`RngCore`] to a [`RngReadAdapter`].
#[cfg(feature = "std")]
fn read_adapter(&mut self) -> RngReadAdapter<'_, Self>
where
Self: Sized,
{
RngReadAdapter { inner: self }
}
}
// Note that, unfortunately, this blanket impl prevents us from implementing
// `TryRngCore` for types which can be dereferenced to `TryRngCore`, i.e. `TryRngCore`
// will not be automatically implemented for `&mut R`, `Box<R>`, etc.
impl<R: RngCore + ?Sized> TryRngCore for R {
type Error = core::convert::Infallible;
#[inline]
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
Ok(self.next_u32())
}
#[inline]
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
Ok(self.next_u64())
}
#[inline]
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
self.fill_bytes(dst);
Ok(())
}
}
/// A marker trait over [`TryRngCore`] for securely unpredictable RNGs
///
/// This trait is like [`CryptoRng`] but for the trait [`TryRngCore`].
///
/// 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.
///
/// Implementors of `TryCryptoRng` should only implement [`Default`] if the
/// `default()` instances are themselves secure generators: for example if the
/// implementing type is a stateless interface over a secure external generator
/// (like [`OsRng`]) or if the `default()` instance uses a strong, fresh seed.
pub trait TryCryptoRng: TryRngCore {}
impl<R: CryptoRng + ?Sized> TryCryptoRng for R {}
/// Wrapper around [`TryRngCore`] implementation which implements [`RngCore`]
/// by panicking on potential errors.
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
pub struct UnwrapErr<R: TryRngCore>(pub R);
impl<R: TryRngCore> RngCore for UnwrapErr<R> {
#[inline]
fn next_u32(&mut self) -> u32 {
self.0.try_next_u32().unwrap()
}
#[inline]
fn next_u64(&mut self) -> u64 {
self.0.try_next_u64().unwrap()
}
#[inline]
fn fill_bytes(&mut self, dst: &mut [u8]) {
self.0.try_fill_bytes(dst).unwrap()
}
}
impl<R: TryCryptoRng> CryptoRng for UnwrapErr<R> {}
/// Wrapper around [`TryRngCore`] implementation which implements [`RngCore`]
/// by panicking on potential errors.
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct UnwrapMut<'r, R: TryRngCore + ?Sized>(pub &'r mut R);
impl<'r, R: TryRngCore + ?Sized> UnwrapMut<'r, 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) -> UnwrapMut<'b, R>
where
'r: 'b,
{
UnwrapMut(self.0)
}
}
impl<R: TryRngCore + ?Sized> RngCore for UnwrapMut<'_, R> {
#[inline]
fn next_u32(&mut self) -> u32 {
self.0.try_next_u32().unwrap()
}
#[inline]
fn next_u64(&mut self) -> u64 {
self.0.try_next_u64().unwrap()
}
#[inline]
fn fill_bytes(&mut self, dst: &mut [u8]) {
self.0.try_fill_bytes(dst).unwrap()
}
}
impl<R: TryCryptoRng + ?Sized> CryptoRng for UnwrapMut<'_, R> {}
/// 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.
///
/// [`rand`]: https://docs.rs/rand
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 {
// We use PCG32 to generate a u32 sequence, and copy to the seed
fn pcg32(state: &mut u64) -> [u8; 4] {
const MUL: u64 = 6364136223846793005;
const INC: u64 = 11634580027462260723;
// 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()
}
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(rng: &mut impl RngCore) -> 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: TryRngCore>(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))
}
/// Creates a new instance of the RNG seeded via [`getrandom`].
///
/// This method is the recommended way to construct non-deterministic PRNGs
/// since it is convenient and secure.
///
/// Note that this method may panic on (extremely unlikely) [`getrandom`] errors.
/// If it's not desirable, use the [`try_from_os_rng`] method instead.
///
/// In case the overhead of using [`getrandom`] to seed *many* PRNGs is an
/// issue, one may prefer to seed from a local PRNG, e.g.
/// `from_rng(rand::rng()).unwrap()`.
///
/// # Panics
///
/// If [`getrandom`] is unable to provide secure entropy this method will panic.
///
/// [`getrandom`]: https://docs.rs/getrandom
/// [`try_from_os_rng`]: SeedableRng::try_from_os_rng
#[cfg(feature = "os_rng")]
fn from_os_rng() -> Self {
match Self::try_from_os_rng() {
Ok(res) => res,
Err(err) => panic!("from_os_rng failed: {}", err),
}
}
/// Creates a new instance of the RNG seeded via [`getrandom`] without unwrapping
/// potential [`getrandom`] errors.
///
/// In case the overhead of using [`getrandom`] to seed *many* PRNGs is an
/// issue, one may prefer to seed from a local PRNG, e.g.
/// `from_rng(&mut rand::rng()).unwrap()`.
///
/// [`getrandom`]: https://docs.rs/getrandom
#[cfg(feature = "os_rng")]
fn try_from_os_rng() -> Result<Self, getrandom::Error> {
let mut seed = Self::Seed::default();
getrandom::fill(seed.as_mut())?;
let res = Self::from_seed(seed);
Ok(res)
}
}
/// Adapter that enables reading through a [`io::Read`](std::io::Read) from a [`RngCore`].
///
/// # Examples
///
/// ```no_run
/// # use std::{io, io::Read};
/// # use std::fs::File;
/// # use rand_core::{OsRng, TryRngCore};
///
/// io::copy(&mut OsRng.read_adapter().take(100), &mut File::create("/tmp/random.bytes").unwrap()).unwrap();
/// ```
#[cfg(feature = "std")]
pub struct RngReadAdapter<'a, R: TryRngCore + ?Sized> {
inner: &'a mut R,
}
#[cfg(feature = "std")]
impl<R: TryRngCore + ?Sized> std::io::Read for RngReadAdapter<'_, R> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
self.inner.try_fill_bytes(buf).map_err(|err| {
std::io::Error::new(std::io::ErrorKind::Other, std::format!("RNG error: {err}"))
})?;
Ok(buf.len())
}
}
#[cfg(feature = "std")]
impl<R: TryRngCore + ?Sized> std::fmt::Debug for RngReadAdapter<'_, R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ReadAdapter").finish()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_seed_from_u64() {
struct SeedableNum(u64);
impl SeedableRng for SeedableNum {
type Seed = [u8; 8];
fn from_seed(seed: Self::Seed) -> Self {
let mut x = [0u64; 1];
le::read_u64_into(&seed, &mut x);
SeedableNum(x[0])
}
}
const N: usize = 8;
const SEEDS: [u64; N] = [0u64, 1, 2, 3, 4, 8, 16, -1i64 as u64];
let mut results = [0u64; N];
for (i, seed) in SEEDS.iter().enumerate() {
let SeedableNum(x) = SeedableNum::seed_from_u64(*seed);
results[i] = x;
}
for (i1, r1) in results.iter().enumerate() {
let weight = r1.count_ones();
// This is the binomial distribution B(64, 0.5), so chance of
// weight < 20 is binocdf(19, 64, 0.5) = 7.8e-4, and same for
// weight > 44.
assert!((20..=44).contains(&weight));
for (i2, r2) in results.iter().enumerate() {
if i1 == i2 {
continue;
}
let diff_weight = (r1 ^ r2).count_ones();
assert!(diff_weight >= 20);
}
}
// value-breakage test:
assert_eq!(results[0], 5029875928683246316);
}
// A stub RNG.
struct SomeRng;
impl RngCore for SomeRng {
fn next_u32(&mut self) -> u32 {
unimplemented!()
}
fn next_u64(&mut self) -> u64 {
unimplemented!()
}
fn fill_bytes(&mut self, _: &mut [u8]) {
unimplemented!()
}
}
impl CryptoRng for SomeRng {}
#[test]
fn dyn_rngcore_to_tryrngcore() {
// Illustrates the need for `+ ?Sized` bound in `impl<R: RngCore> TryRngCore for R`.
// A method in another crate taking a fallible RNG
fn third_party_api(_rng: &mut (impl TryRngCore + ?Sized)) -> bool {
true
}
// A method in our crate requiring an infallible RNG
fn my_api(rng: &mut dyn RngCore) -> bool {
// We want to call the method above
third_party_api(rng)
}
assert!(my_api(&mut SomeRng));
}
#[test]
fn dyn_cryptorng_to_trycryptorng() {
// Illustrates the need for `+ ?Sized` bound in `impl<R: CryptoRng> TryCryptoRng for R`.
// A method in another crate taking a fallible RNG
fn third_party_api(_rng: &mut (impl TryCryptoRng + ?Sized)) -> bool {
true
}
// A method in our crate requiring an infallible RNG
fn my_api(rng: &mut dyn CryptoRng) -> bool {
// We want to call the method above
third_party_api(rng)
}
assert!(my_api(&mut SomeRng));
}
#[test]
fn dyn_unwrap_mut_tryrngcore() {
// Illustrates the need for `+ ?Sized` bound in
// `impl<R: TryRngCore> RngCore for UnwrapMut<'_, R>`.
fn third_party_api(_rng: &mut impl RngCore) -> bool {
true
}
fn my_api(rng: &mut (impl TryRngCore + ?Sized)) -> bool {
let mut infallible_rng = rng.unwrap_mut();
third_party_api(&mut infallible_rng)
}
assert!(my_api(&mut SomeRng));
}
#[test]
fn dyn_unwrap_mut_trycryptorng() {
// Illustrates the need for `+ ?Sized` bound in
// `impl<R: TryCryptoRng> CryptoRng for UnwrapMut<'_, R>`.
fn third_party_api(_rng: &mut impl CryptoRng) -> bool {
true
}
fn my_api(rng: &mut (impl TryCryptoRng + ?Sized)) -> bool {
let mut infallible_rng = rng.unwrap_mut();
third_party_api(&mut infallible_rng)
}
assert!(my_api(&mut SomeRng));
}
#[test]
fn reborrow_unwrap_mut() {
struct FourRng;
impl TryRngCore for FourRng {
type Error = core::convert::Infallible;
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
Ok(4)
}
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
unimplemented!()
}
fn try_fill_bytes(&mut self, _: &mut [u8]) -> Result<(), Self::Error> {
unimplemented!()
}
}
let mut rng = FourRng;
let mut rng = rng.unwrap_mut();
assert_eq!(rng.next_u32(), 4);
let mut rng2 = rng.re();
assert_eq!(rng2.next_u32(), 4);
drop(rng2);
assert_eq!(rng.next_u32(), 4);
}
}

115
vendor/rand_core/src/os.rs vendored Normal file
View File

@@ -0,0 +1,115 @@
// Copyright 2019 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Interface to the random number generator of the operating system.
use crate::{TryCryptoRng, TryRngCore};
/// An interface over the operating-system's random data source
///
/// This is a zero-sized struct. It can be freely constructed with just `OsRng`.
///
/// The implementation is provided by the [getrandom] crate. Refer to
/// [getrandom] documentation for details.
///
/// This struct is available as `rand_core::OsRng` and as `rand::rngs::OsRng`.
/// In both cases, this requires the crate feature `os_rng` or `std`
/// (enabled by default in `rand` but not in `rand_core`).
///
/// # Blocking and error handling
///
/// It is possible that when used during early boot the first call to `OsRng`
/// will block until the system's RNG is initialised. It is also possible
/// (though highly unlikely) for `OsRng` to fail on some platforms, most
/// likely due to system mis-configuration.
///
/// After the first successful call, it is highly unlikely that failures or
/// significant delays will occur (although performance should be expected to
/// be much slower than a user-space
/// [PRNG](https://rust-random.github.io/book/guide-gen.html#pseudo-random-number-generators)).
///
/// # Usage example
/// ```
/// use rand_core::{TryRngCore, OsRng};
///
/// let mut key = [0u8; 16];
/// OsRng.try_fill_bytes(&mut key).unwrap();
/// let random_u64 = OsRng.try_next_u64().unwrap();
/// ```
///
/// [getrandom]: https://crates.io/crates/getrandom
#[derive(Clone, Copy, Debug, Default)]
pub struct OsRng;
/// Error type of [`OsRng`]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OsError(getrandom::Error);
impl core::fmt::Display for OsError {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.0.fmt(f)
}
}
// NOTE: this can use core::error::Error from rustc 1.81.0
#[cfg(feature = "std")]
impl std::error::Error for OsError {
#[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
std::error::Error::source(&self.0)
}
}
impl OsError {
/// Extract the raw OS error code (if this error came from the OS)
///
/// This method is identical to [`std::io::Error::raw_os_error()`][1], except
/// that it works in `no_std` contexts. If this method returns `None`, the
/// error value can still be formatted via the `Display` implementation.
///
/// [1]: https://doc.rust-lang.org/std/io/struct.Error.html#method.raw_os_error
#[inline]
pub fn raw_os_error(self) -> Option<i32> {
self.0.raw_os_error()
}
}
impl TryRngCore for OsRng {
type Error = OsError;
#[inline]
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
getrandom::u32().map_err(OsError)
}
#[inline]
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
getrandom::u64().map_err(OsError)
}
#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
getrandom::fill(dest).map_err(OsError)
}
}
impl TryCryptoRng for OsRng {}
#[test]
fn test_os_rng() {
let x = OsRng.try_next_u64().unwrap();
let y = OsRng.try_next_u64().unwrap();
assert!(x != 0);
assert!(x != y);
}
#[test]
fn test_construction() {
assert!(OsRng.try_next_u64().unwrap() != 0);
}