2026-07-01 20:48:44 +02:00
|
|
|
// SPDX-License-Identifier: MIT OR Apache-2.0
|
|
|
|
|
// Copyright (c) VexaHub and contributors.
|
2023-05-22 23:04:26 -07:00
|
|
|
// Copyright (c) Meta Platforms, Inc. and affiliates.
|
2020-06-05 09:35:14 -07:00
|
|
|
|
2021-08-12 06:25:07 +02:00
|
|
|
use core::cmp::min;
|
2022-01-06 00:10:57 +01:00
|
|
|
use std::vec::Vec;
|
2020-06-05 09:35:14 -07:00
|
|
|
|
2026-07-01 11:52:12 +02:00
|
|
|
use core::convert::Infallible;
|
2026-07-02 08:19:22 +02:00
|
|
|
use rand::rand_core::{TryCryptoRng, TryRng};
|
2022-01-06 06:19:02 +01:00
|
|
|
|
2026-07-01 11:52:12 +02:00
|
|
|
/// A simple implementation of `Rng` for testing purposes.
|
2020-06-05 09:35:14 -07:00
|
|
|
///
|
|
|
|
|
/// This generates a cyclic sequence (i.e. cycles over an initial buffer)
|
2022-01-04 00:50:40 +01:00
|
|
|
#[derive(Clone, Debug)]
|
2020-06-05 09:35:14 -07:00
|
|
|
pub struct CycleRng {
|
|
|
|
|
v: Vec<u8>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl CycleRng {
|
2022-01-06 06:19:02 +01:00
|
|
|
/// Create a `CycleRng`, yielding a sequence starting with `initial` and
|
|
|
|
|
/// looping thereafter
|
2020-06-05 09:35:14 -07:00
|
|
|
pub fn new(initial: Vec<u8>) -> Self {
|
|
|
|
|
CycleRng { v: initial }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn rotate_left<T>(data: &mut [T], steps: usize) {
|
|
|
|
|
if data.is_empty() {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
let steps = steps % data.len();
|
|
|
|
|
|
|
|
|
|
data[..steps].reverse();
|
|
|
|
|
data[steps..].reverse();
|
|
|
|
|
data.reverse();
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-01 11:52:12 +02:00
|
|
|
impl TryRng for CycleRng {
|
|
|
|
|
type Error = Infallible;
|
|
|
|
|
|
|
|
|
|
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
|
|
|
|
|
let mut buf = [0u8; 4];
|
|
|
|
|
|
|
|
|
|
self.try_fill_bytes(&mut buf)?;
|
|
|
|
|
|
|
|
|
|
Ok(u32::from_le_bytes(buf))
|
2020-06-05 09:35:14 -07:00
|
|
|
}
|
|
|
|
|
|
2026-07-01 11:52:12 +02:00
|
|
|
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
|
|
|
|
|
let mut buf = [0u8; 8];
|
|
|
|
|
|
|
|
|
|
self.try_fill_bytes(&mut buf)?;
|
|
|
|
|
|
|
|
|
|
Ok(u64::from_le_bytes(buf))
|
2020-06-05 09:35:14 -07:00
|
|
|
}
|
|
|
|
|
|
2026-07-01 11:52:12 +02:00
|
|
|
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
|
2020-06-05 09:35:14 -07:00
|
|
|
let len = min(self.v.len(), dest.len());
|
2026-07-01 11:52:12 +02:00
|
|
|
|
2022-12-10 23:21:56 +01:00
|
|
|
dest[..len].copy_from_slice(&self.v[..len]);
|
2026-07-01 11:52:12 +02:00
|
|
|
|
2020-06-05 09:35:14 -07:00
|
|
|
rotate_left(&mut self.v, len);
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// This is meant for testing only
|
2026-07-01 11:52:12 +02:00
|
|
|
impl TryCryptoRng for CycleRng {}
|