Add random number generator

9e33f884e8b5d2e7982b72ced83e399e534a635c
Provide seeded WyRand generation, uniform ranges, byte filling,
selection, and shuffling without adding a dependency.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent 7c326dc0
src/lib.rs +7 -0
18 18
19 19
/// Line editing with history and cursor movement.
20 20
#[allow(unsafe_code)]
21 21
pub mod readline;
22 22
23 +
/// Numerical traits used by the random number generator.
24 +
pub mod math;
25 +
26 +
/// Random number generation using the WyRand algorithm.
27 +
#[allow(unsafe_code)]
28 +
pub mod rng;
29 +
23 30
/// Re-export of the facade crate.
24 31
pub use rustik_tui as tui;
25 32
26 33
/// Re-export of the unified diff parser and viewer crate.
27 34
#[cfg(feature = "diff")]
src/math.rs added +7 -0
1 +
//! Numerical traits required by the random number generator.
2 +
3 +
pub mod macros;
4 +
#[allow(unsafe_code)]
5 +
pub mod traits;
6 +
7 +
pub use traits::{Bounded, One};
src/math/macros.rs added +33 -0
1 +
//! Some useful macros.
2 +
3 +
/// Assertion macro for [`crate::math::traits::ApproxEq::approx_eq`].
4 +
#[macro_export]
5 +
macro_rules! assert_approx_eq {
6 +
    ($a:expr, $b:expr, $epsilon:expr) => {{
7 +
        let (a, b, eps) = ($a, $b, $epsilon);
8 +
        assert!(
9 +
            $crate::math::traits::ApproxEq::approx_eq(&a, &b, eps),
10 +
            "\
11 +
assertion `|left - right| <= {eps}` failed
12 +
  left: {a}
13 +
 right: {b}"
14 +
        );
15 +
    }};
16 +
}
17 +
pub use assert_approx_eq;
18 +
19 +
/// Assertion macro for [`crate::math::traits::ApproxEq::approx_neq`].
20 +
#[macro_export]
21 +
macro_rules! assert_approx_neq {
22 +
    ($a:expr, $b:expr, $epsilon:expr) => {{
23 +
        let (a, b, eps) = ($a, $b, $epsilon);
24 +
        assert!(
25 +
            $crate::math::traits::ApproxEq::approx_neq(&a, &b, eps),
26 +
            "\
27 +
assertion `|left - right| > {eps}` failed
28 +
  left: {a}
29 +
 right: {b}"
30 +
        );
31 +
    }};
32 +
}
33 +
pub use assert_approx_neq;
src/math/traits.rs added +508 -0
1 +
//! Numerical traits.
2 +
#![allow(missing_docs, clippy::useless_nonzero_new_unchecked)]
3 +
use std::num::NonZeroU8;
4 +
use std::ops::{Add, Div, Mul, Neg, Shl, Sub};
5 +
6 +
/// A type that has a "zero".
7 +
pub trait Zero: PartialEq + Sized {
8 +
    const ZERO: Self;
9 +
10 +
    fn is_zero(&self) -> bool;
11 +
}
12 +
13 +
impl Zero for f32 {
14 +
    const ZERO: f32 = 0.;
15 +
16 +
    fn is_zero(&self) -> bool {
17 +
        self == &Self::ZERO
18 +
    }
19 +
}
20 +
21 +
impl Zero for f64 {
22 +
    const ZERO: f64 = 0.;
23 +
24 +
    fn is_zero(&self) -> bool {
25 +
        self == &Self::ZERO
26 +
    }
27 +
}
28 +
29 +
impl Zero for usize {
30 +
    const ZERO: usize = 0;
31 +
32 +
    fn is_zero(&self) -> bool {
33 +
        self == &Self::ZERO
34 +
    }
35 +
}
36 +
37 +
impl Zero for i32 {
38 +
    const ZERO: i32 = 0;
39 +
40 +
    fn is_zero(&self) -> bool {
41 +
        self == &Self::ZERO
42 +
    }
43 +
}
44 +
45 +
impl Zero for u8 {
46 +
    const ZERO: u8 = 0;
47 +
48 +
    fn is_zero(&self) -> bool {
49 +
        self == &Self::ZERO
50 +
    }
51 +
}
52 +
53 +
impl Zero for u16 {
54 +
    const ZERO: u16 = 0;
55 +
56 +
    fn is_zero(&self) -> bool {
57 +
        self == &Self::ZERO
58 +
    }
59 +
}
60 +
61 +
impl Zero for u32 {
62 +
    const ZERO: u32 = 0;
63 +
64 +
    fn is_zero(&self) -> bool {
65 +
        self == &Self::ZERO
66 +
    }
67 +
}
68 +
69 +
impl Zero for u64 {
70 +
    const ZERO: u64 = 0;
71 +
72 +
    fn is_zero(&self) -> bool {
73 +
        self == &Self::ZERO
74 +
    }
75 +
}
76 +
77 +
impl Zero for i64 {
78 +
    const ZERO: i64 = 0;
79 +
80 +
    fn is_zero(&self) -> bool {
81 +
        self == &Self::ZERO
82 +
    }
83 +
}
84 +
85 +
////////////////////////////////////////////////////////////////////////////////
86 +
87 +
/// A type that has a "one".
88 +
pub trait One: Sized {
89 +
    const ONE: Self;
90 +
91 +
    fn is_one(&self) -> bool;
92 +
}
93 +
94 +
impl One for f32 {
95 +
    const ONE: f32 = 1.;
96 +
97 +
    fn is_one(&self) -> bool {
98 +
        self == &Self::ONE
99 +
    }
100 +
}
101 +
102 +
impl One for f64 {
103 +
    const ONE: f64 = 1.;
104 +
105 +
    fn is_one(&self) -> bool {
106 +
        self == &Self::ONE
107 +
    }
108 +
}
109 +
110 +
impl One for usize {
111 +
    const ONE: usize = 1;
112 +
113 +
    fn is_one(&self) -> bool {
114 +
        self == &Self::ONE
115 +
    }
116 +
}
117 +
118 +
impl One for u8 {
119 +
    const ONE: u8 = 1;
120 +
121 +
    fn is_one(&self) -> bool {
122 +
        self == &Self::ONE
123 +
    }
124 +
}
125 +
126 +
impl One for u32 {
127 +
    const ONE: u32 = 1;
128 +
129 +
    fn is_one(&self) -> bool {
130 +
        self == &Self::ONE
131 +
    }
132 +
}
133 +
134 +
impl One for u64 {
135 +
    const ONE: u64 = 1;
136 +
137 +
    fn is_one(&self) -> bool {
138 +
        self == &Self::ONE
139 +
    }
140 +
}
141 +
142 +
impl One for i32 {
143 +
    const ONE: i32 = 1;
144 +
145 +
    fn is_one(&self) -> bool {
146 +
        self == &Self::ONE
147 +
    }
148 +
}
149 +
150 +
impl One for NonZeroU8 {
151 +
    const ONE: NonZeroU8 = unsafe { NonZeroU8::new_unchecked(u8::ONE) };
152 +
153 +
    fn is_one(&self) -> bool {
154 +
        self == &Self::ONE
155 +
    }
156 +
}
157 +
158 +
////////////////////////////////////////////////////////////////////////////////
159 +
160 +
/// A type that has a "two".
161 +
pub trait Two {
162 +
    const TWO: Self;
163 +
}
164 +
165 +
impl Two for f32 {
166 +
    const TWO: f32 = 2.;
167 +
}
168 +
169 +
impl Two for f64 {
170 +
    const TWO: f64 = 2.;
171 +
}
172 +
173 +
impl Two for i32 {
174 +
    const TWO: i32 = 2;
175 +
}
176 +
177 +
////////////////////////////////////////////////////////////////////////////////
178 +
179 +
/// Trait for types with defined minimum and maximum bounds.
180 +
pub trait Bounded {
181 +
    /// Minimum value for this type.
182 +
    const MIN: Self;
183 +
    /// Maximum value for this type.
184 +
    const MAX: Self;
185 +
}
186 +
187 +
impl Bounded for u8 {
188 +
    const MIN: Self = u8::MIN;
189 +
    const MAX: Self = u8::MAX;
190 +
}
191 +
192 +
impl Bounded for u16 {
193 +
    const MIN: Self = u16::MIN;
194 +
    const MAX: Self = u16::MAX;
195 +
}
196 +
197 +
impl Bounded for u32 {
198 +
    const MIN: Self = u32::MIN;
199 +
    const MAX: Self = u32::MAX;
200 +
}
201 +
202 +
impl Bounded for u64 {
203 +
    const MIN: Self = u64::MIN;
204 +
    const MAX: Self = u64::MAX;
205 +
}
206 +
207 +
impl Bounded for i8 {
208 +
    const MIN: Self = i8::MIN;
209 +
    const MAX: Self = i8::MAX;
210 +
}
211 +
212 +
impl Bounded for i16 {
213 +
    const MIN: Self = i16::MIN;
214 +
    const MAX: Self = i16::MAX;
215 +
}
216 +
217 +
impl Bounded for i32 {
218 +
    const MIN: Self = i32::MIN;
219 +
    const MAX: Self = i32::MAX;
220 +
}
221 +
222 +
impl Bounded for i64 {
223 +
    const MIN: Self = i64::MIN;
224 +
    const MAX: Self = i64::MAX;
225 +
}
226 +
227 +
impl Bounded for f64 {
228 +
    const MIN: Self = f64::MIN;
229 +
    const MAX: Self = f64::MAX;
230 +
}
231 +
232 +
impl Bounded for f32 {
233 +
    const MIN: Self = f32::MIN;
234 +
    const MAX: Self = f32::MAX;
235 +
}
236 +
237 +
impl Bounded for usize {
238 +
    const MIN: Self = usize::MIN;
239 +
    const MAX: Self = usize::MAX;
240 +
}
241 +
242 +
////////////////////////////////////////////////////////////////////////////////
243 +
244 +
/// Trait defining operations and properties required for integer types.
245 +
pub trait Integer:
246 +
    Copy
247 +
    + Ord
248 +
    + One
249 +
    + Zero
250 +
    + Bounded
251 +
    + Add<Output = Self>
252 +
    + Sub<Output = Self>
253 +
    + Shl<u32, Output = Self>
254 +
{
255 +
    /// Number of bits in this integer type.
256 +
    const BITS: u32;
257 +
258 +
    /// Converts a [`u64`] to this integer type.
259 +
    fn from_u64(other: u64) -> Self;
260 +
    /// Converts this integer to [`u64`].
261 +
    fn as_u64(&self) -> u64;
262 +
    /// Wrapping add.
263 +
    fn wrapping_add(self, rhs: Self) -> Self;
264 +
    /// Wrapping sub.
265 +
    fn wrapping_sub(self, rhs: Self) -> Self;
266 +
}
267 +
268 +
impl Integer for u32 {
269 +
    const BITS: u32 = u32::BITS;
270 +
271 +
    fn from_u64(other: u64) -> Self {
272 +
        other as u32
273 +
    }
274 +
275 +
    fn as_u64(&self) -> u64 {
276 +
        *self as u64
277 +
    }
278 +
279 +
    fn wrapping_add(self, rhs: Self) -> Self {
280 +
        self.wrapping_add(rhs)
281 +
    }
282 +
283 +
    fn wrapping_sub(self, rhs: Self) -> Self {
284 +
        self.wrapping_sub(rhs)
285 +
    }
286 +
}
287 +
288 +
impl Integer for i32 {
289 +
    const BITS: u32 = i32::BITS;
290 +
291 +
    fn from_u64(other: u64) -> Self {
292 +
        other as u32 as i32
293 +
    }
294 +
295 +
    fn as_u64(&self) -> u64 {
296 +
        *self as u32 as u64
297 +
    }
298 +
299 +
    fn wrapping_add(self, rhs: Self) -> Self {
300 +
        self.wrapping_add(rhs)
301 +
    }
302 +
303 +
    fn wrapping_sub(self, rhs: Self) -> Self {
304 +
        self.wrapping_sub(rhs)
305 +
    }
306 +
}
307 +
308 +
impl Integer for u64 {
309 +
    const BITS: u32 = u64::BITS;
310 +
311 +
    fn from_u64(other: u64) -> Self {
312 +
        other
313 +
    }
314 +
315 +
    fn as_u64(&self) -> u64 {
316 +
        *self
317 +
    }
318 +
319 +
    fn wrapping_add(self, rhs: Self) -> Self {
320 +
        self.wrapping_add(rhs)
321 +
    }
322 +
323 +
    fn wrapping_sub(self, rhs: Self) -> Self {
324 +
        self.wrapping_sub(rhs)
325 +
    }
326 +
}
327 +
328 +
impl Integer for usize {
329 +
    const BITS: u32 = usize::BITS;
330 +
331 +
    fn from_u64(other: u64) -> Self {
332 +
        other as usize
333 +
    }
334 +
335 +
    fn as_u64(&self) -> u64 {
336 +
        *self as u64
337 +
    }
338 +
339 +
    fn wrapping_add(self, rhs: Self) -> Self {
340 +
        self.wrapping_add(rhs)
341 +
    }
342 +
343 +
    fn wrapping_sub(self, rhs: Self) -> Self {
344 +
        self.wrapping_sub(rhs)
345 +
    }
346 +
}
347 +
348 +
////////////////////////////////////////////////////////////////////////////////
349 +
350 +
/// Floating point numbers.
351 +
pub trait Float:
352 +
    Copy
353 +
    + PartialOrd
354 +
    + Zero
355 +
    + One
356 +
    + Two
357 +
    + Neg<Output = Self>
358 +
    + Add<Output = Self>
359 +
    + Sub<Output = Self>
360 +
    + Div<Output = Self>
361 +
    + Mul<Output = Self>
362 +
{
363 +
    /// Get the square root.
364 +
    fn sqrt(self) -> Self;
365 +
}
366 +
367 +
impl Float for f32 {
368 +
    fn sqrt(self) -> Self {
369 +
        f32::sqrt(self)
370 +
    }
371 +
}
372 +
373 +
impl Float for f64 {
374 +
    fn sqrt(self) -> Self {
375 +
        f64::sqrt(self)
376 +
    }
377 +
}
378 +
379 +
/// Adds convenience methods to `f32` and `f64`.
380 +
pub trait FloatExt<T> {
381 +
    /// Rounds to the nearest integer towards zero,
382 +
    /// unless the provided value is already an integer.
383 +
    ///
384 +
    /// It is to `floor` what `expand` is to `ceil`.
385 +
    ///
386 +
    /// # Examples
387 +
    ///
388 +
    /// ```
389 +
    /// use rustik::math::traits::FloatExt;
390 +
    ///
391 +
    /// let f = 3.7_f64;
392 +
    /// let g = 3.0_f64;
393 +
    /// let h = -3.7_f64;
394 +
    /// let i = -5.9_f32;
395 +
    ///
396 +
    /// assert_eq!(f.truncate(), 3.0);
397 +
    /// assert_eq!(g.truncate(), 3.0);
398 +
    /// assert_eq!(h.truncate(), -3.0);
399 +
    /// assert_eq!(i.truncate(), -5.0);
400 +
    /// ```
401 +
    fn truncate(&self) -> T;
402 +
403 +
    /// Rounds to the nearest integer away from zero,
404 +
    /// unless the provided value is already an integer.
405 +
    ///
406 +
    /// It is to `ceil` what `truncate` is to `floor`.
407 +
    ///
408 +
    /// # Examples
409 +
    ///
410 +
    /// ```
411 +
    /// use rustik::math::traits::FloatExt;
412 +
    ///
413 +
    /// let f = 3.7_f64;
414 +
    /// let g = 3.0_f64;
415 +
    /// let h = -3.7_f64;
416 +
    /// let i = -5.1_f32;
417 +
    ///
418 +
    /// assert_eq!(f.expand(), 4.0);
419 +
    /// assert_eq!(g.expand(), 3.0);
420 +
    /// assert_eq!(h.expand(), -4.0);
421 +
    /// assert_eq!(i.expand(), -6.0);
422 +
    /// ```
423 +
    fn expand(&self) -> T;
424 +
}
425 +
426 +
impl FloatExt<f64> for f64 {
427 +
    #[inline]
428 +
    fn expand(&self) -> f64 {
429 +
        self.abs().ceil().copysign(*self)
430 +
    }
431 +
432 +
    #[inline]
433 +
    fn truncate(&self) -> Self {
434 +
        self.abs().floor().copysign(*self)
435 +
    }
436 +
}
437 +
438 +
impl FloatExt<f32> for f32 {
439 +
    #[inline]
440 +
    fn expand(&self) -> f32 {
441 +
        self.abs().ceil().copysign(*self)
442 +
    }
443 +
444 +
    #[inline]
445 +
    fn truncate(&self) -> Self {
446 +
        self.abs().floor().copysign(*self)
447 +
    }
448 +
}
449 +
450 +
/// Approximate equality.
451 +
pub trait ApproxEq {
452 +
    type Epsilon: Copy + PartialOrd;
453 +
454 +
    /// Checks if `|x - y| <= epsilon`.
455 +
    fn approx_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool;
456 +
    /// Checks if `|x - y| > epsilon`.
457 +
    fn approx_neq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
458 +
        !self.approx_eq(other, epsilon)
459 +
    }
460 +
}
461 +
462 +
impl ApproxEq for f32 {
463 +
    type Epsilon = f32;
464 +
465 +
    fn approx_eq(&self, other: &Self, epsilon: f32) -> bool {
466 +
        (self - other).abs() <= epsilon
467 +
    }
468 +
}
469 +
470 +
impl ApproxEq for f64 {
471 +
    type Epsilon = f64;
472 +
473 +
    fn approx_eq(&self, other: &Self, epsilon: f64) -> bool {
474 +
        (self - other).abs() <= epsilon
475 +
    }
476 +
}
477 +
478 +
#[cfg(test)]
479 +
mod test {
480 +
    use super::*;
481 +
    use crate::math::macros::*;
482 +
483 +
    #[test]
484 +
    fn test_approx_eq() {
485 +
        assert_approx_eq!(1.0, 1.0, 0.0001);
486 +
        assert_approx_eq!(1.0, 1.001, 0.01);
487 +
        assert_approx_neq!(1.0, 1.001, 0.00000001);
488 +
    }
489 +
490 +
    #[test]
491 +
    fn test_integer_wrapping() {
492 +
        let max_u32 = u32::MAX;
493 +
        assert_eq!(max_u32.wrapping_add(1), 0);
494 +
        assert_eq!(0_u32.wrapping_sub(1), max_u32);
495 +
496 +
        let max_i32 = i32::MAX;
497 +
        assert_eq!(max_i32.wrapping_add(1), i32::MIN);
498 +
        assert_eq!(i32::MIN.wrapping_sub(1), i32::MAX);
499 +
    }
500 +
501 +
    #[test]
502 +
    fn test_integer_conversions() {
503 +
        assert_eq!(42_u32.as_u64(), 42_u64);
504 +
        assert_eq!(42_i32.as_u64(), 42_u64);
505 +
        assert_eq!(42_u64.as_u64(), 42_u64);
506 +
        assert_eq!(42_usize.as_u64(), 42_u64);
507 +
    }
508 +
}
src/rng.rs added +486 -0
1 +
//! Random number generator.
2 +
// (c) Simon Heath, some quality nuggets from their `oorandom` crate
3 +
// (c) Wang Yi, WyRand algorithm
4 +
// (c) The `fastrand` authors, various tidbits
5 +
#![warn(missing_docs)]
6 +
#![allow(clippy::panic)]
7 +
8 +
use std::collections::hash_map::DefaultHasher;
9 +
use std::hash::{Hash, Hasher};
10 +
use std::ops::{Add, Bound, RangeBounds, Sub};
11 +
use std::time::Instant;
12 +
use std::{fmt, thread};
13 +
14 +
use crate::math::traits::Integer;
15 +
use crate::math::{Bounded, One};
16 +
17 +
/// Trait for sources of entropy.
18 +
pub trait Entropy {
19 +
    /// Generate a random [`u64`].
20 +
    fn gen_u64(&mut self) -> u64;
21 +
22 +
    /// Generate a random [`u32`].
23 +
    #[inline]
24 +
    fn gen_u32(&mut self) -> u32 {
25 +
        self.gen_u64() as u32
26 +
    }
27 +
}
28 +
29 +
/// A type that can be randomly generated
30 +
/// A probability distribution that can generate random values.
31 +
/// Implementations define how to sample values of type T from a random source.
32 +
pub trait Distribution<T> {
33 +
    /// Generates a random value from this distribution using the given entropy source.
34 +
    fn sample<R: Entropy>(&self, rng: &mut R) -> T;
35 +
}
36 +
37 +
#[cfg(target_os = "linux")]
38 +
unsafe extern "C" {
39 +
    fn getrandom(buf: *mut u8, buflen: usize, flags: u32) -> isize;
40 +
}
41 +
42 +
/// Attempts to fill a buffer from the operating system's non-blocking entropy source.
43 +
#[cfg(target_os = "linux")]
44 +
fn random(out: &mut [u8]) -> bool {
45 +
    const GRND_NONBLOCK: u32 = 0x0001;
46 +
47 +
    unsafe { getrandom(out.as_mut_ptr(), out.len(), GRND_NONBLOCK) as usize == out.len() }
48 +
}
49 +
50 +
/// Reports unavailable direct system entropy on unsupported targets.
51 +
#[cfg(not(target_os = "linux"))]
52 +
fn random(_out: &mut [u8]) -> bool {
53 +
    false
54 +
}
55 +
56 +
/// The main RNG using WyRand algorithm
57 +
#[derive(Debug, Clone)]
58 +
pub struct Rng {
59 +
    state: u64,
60 +
}
61 +
62 +
impl Default for Rng {
63 +
    fn default() -> Self {
64 +
        Self::new()
65 +
    }
66 +
}
67 +
68 +
impl Rng {
69 +
    /// Creates a new RNG with a random seed derived from system entropy.
70 +
    #[inline]
71 +
    pub fn new() -> Self {
72 +
        let mut bytes = [0u8; 8];
73 +
        let seed = if random(&mut bytes) {
74 +
            u64::from_ne_bytes(bytes)
75 +
        } else {
76 +
            let mut hasher = DefaultHasher::new();
77 +
            Instant::now().hash(&mut hasher);
78 +
            thread::current().id().hash(&mut hasher);
79 +
80 +
            hasher.finish()
81 +
        };
82 +
        Self::with_seed(seed)
83 +
    }
84 +
85 +
    /// Samples a value from the given distribution.
86 +
    pub fn sample<T>(&mut self, dist: &impl Distribution<T>) -> T {
87 +
        dist.sample(self)
88 +
    }
89 +
90 +
    /// Creates a new RNG with the specified seed for deterministic generation.
91 +
    #[inline]
92 +
    pub fn with_seed(seed: u64) -> Self {
93 +
        Self { state: seed }
94 +
    }
95 +
96 +
    /// Generates a random float in the range `[0.0, 1.0)` with 53 bits of precision.
97 +
    ///
98 +
    /// This provides high-quality uniformly distributed floating point numbers suitable
99 +
    /// for most applications requiring random real numbers.
100 +
    pub fn fraction(&mut self) -> f64 {
101 +
        const PRECISION: u32 = f64::MANTISSA_DIGITS;
102 +
        const MANTISSA_SCALE: f64 = 1.0 / ((1u64 << PRECISION) as f64);
103 +
104 +
        let mut r = self.gen_u64();
105 +
106 +
        r >>= 64 - PRECISION;
107 +
        r as f64 * MANTISSA_SCALE
108 +
    }
109 +
110 +
    /// Generates a random value of type `T` within the given range.
111 +
    /// Panics if the range is empty.
112 +
    #[inline]
113 +
    pub fn generate<T>(&mut self, range: impl RangeBounds<T>) -> T
114 +
    where
115 +
        T: Copy + PartialOrd + Sub<Output = T> + Add<Output = T> + Bounded + One + fmt::Debug,
116 +
        Uniform<T>: Distribution<T>,
117 +
    {
118 +
        Uniform::from_range(range).sample(self)
119 +
    }
120 +
121 +
    /// Generates a random boolean with 50/50 probability.
122 +
    #[inline]
123 +
    pub fn flip(&mut self) -> bool {
124 +
        self.gen_u32() & 1 == 1
125 +
    }
126 +
127 +
    /// Clones the generator by deterministically deriving a new generator based on the initial
128 +
    /// seed.
129 +
    ///
130 +
    /// This function can be used to create a new generator that is a "spinoff" of the old
131 +
    /// generator. The new generator will not produce the same sequence of values as the
132 +
    /// old generator.
133 +
    #[inline]
134 +
    #[must_use]
135 +
    pub fn fork(&mut self) -> Self {
136 +
        Rng::with_seed(self.gen_u64())
137 +
    }
138 +
139 +
    /// Randomly shuffles the elements of the slice in place using Fisher-Yates algorithm.
140 +
    #[inline]
141 +
    pub fn shuffle<T>(&mut self, slice: &mut [T]) {
142 +
        for i in 1..slice.len() {
143 +
            slice.swap(i, self.generate(..=i));
144 +
        }
145 +
    }
146 +
147 +
    /// Fills a byte slice with random values.
148 +
    pub fn fill(&mut self, slice: &mut [u8]) {
149 +
        // We fill the slice by chunks of 8 bytes, or one block of
150 +
        // WyRand output per new state.
151 +
        let mut chunks = slice.chunks_exact_mut(core::mem::size_of::<u64>());
152 +
        for chunk in chunks.by_ref() {
153 +
            let n = self.gen_u64().to_ne_bytes();
154 +
            // Safe because the chunks are always 8 bytes exactly.
155 +
            chunk.copy_from_slice(&n);
156 +
        }
157 +
158 +
        // Any remainder will always be less than 8 bytes.
159 +
        let remainder = chunks.into_remainder();
160 +
        if !remainder.is_empty() {
161 +
            // Generate one last block of 8 bytes of entropy
162 +
            let n = self.gen_u64().to_ne_bytes();
163 +
            // Use the remaining length to copy from block
164 +
            remainder.copy_from_slice(&n[..remainder.len()]);
165 +
        }
166 +
    }
167 +
168 +
    /// Returns a random reference to an element from the slice, or None if empty.
169 +
    #[inline]
170 +
    pub fn choose<'a, T>(&mut self, slice: &'a [T]) -> Option<&'a T> {
171 +
        if slice.is_empty() {
172 +
            None
173 +
        } else {
174 +
            Some(&slice[self.generate(..slice.len())])
175 +
        }
176 +
    }
177 +
178 +
    /// Returns a random mutable reference to an element from the slice, or None if empty.
179 +
    #[inline]
180 +
    pub fn choose_mut<'a, T>(&mut self, slice: &'a mut [T]) -> Option<&'a mut T> {
181 +
        if slice.is_empty() {
182 +
            None
183 +
        } else {
184 +
            let idx = self.generate(0..slice.len());
185 +
            Some(&mut slice[idx])
186 +
        }
187 +
    }
188 +
}
189 +
190 +
impl Entropy for Rng {
191 +
    #[inline(always)]
192 +
    fn gen_u64(&mut self) -> u64 {
193 +
        self.state = self.state.wrapping_add(0x2d35_8dcc_aa6c_78a5);
194 +
        let t = u128::from(self.state) * u128::from(self.state ^ 0x8bb8_4b93_962e_acc9);
195 +
        (t as u64) ^ (t >> 64) as u64
196 +
    }
197 +
}
198 +
199 +
/// Uniform distribution over a range.
200 +
#[derive(Debug, Clone, Copy)]
201 +
pub struct Uniform<T> {
202 +
    low: T,
203 +
    high: T,
204 +
}
205 +
206 +
impl<T> Uniform<T> {
207 +
    /// Creates a new uniform distribution over the range `[low, high]`.
208 +
    #[inline]
209 +
    pub const fn new(low: T, high: T) -> Self {
210 +
        Self { low, high }
211 +
    }
212 +
}
213 +
214 +
impl<T: Bounded> Uniform<T> {
215 +
    /// Creates a uniform distribution over the full range of the type `T`.
216 +
    ///
217 +
    /// This distribution will generate values across the entire range of valid values
218 +
    /// for the bounded type `T`, from `T::MIN` to `T::MAX` inclusive.
219 +
    #[inline]
220 +
    pub const fn full() -> Self {
221 +
        Self::new(T::MIN, T::MAX)
222 +
    }
223 +
224 +
    /// Like [`Self::full`], but with a specified range.
225 +
    #[inline]
226 +
    pub fn from_range<R: RangeBounds<T>>(range: R) -> Self
227 +
    where
228 +
        T: Copy + PartialOrd + Add<Output = T> + Sub<Output = T> + fmt::Debug + One,
229 +
    {
230 +
        let low = match range.start_bound() {
231 +
            Bound::Unbounded => T::MIN,
232 +
            Bound::Included(&x) => x,
233 +
            Bound::Excluded(&x) if x < T::MAX => x + T::ONE,
234 +
            Bound::Excluded(_) => panic!(
235 +
                "Uniform::from_range: empty range {:?}..{:?}",
236 +
                range.start_bound(),
237 +
                range.end_bound()
238 +
            ),
239 +
        };
240 +
        let high = match range.end_bound() {
241 +
            Bound::Unbounded => T::MAX,
242 +
            Bound::Included(&x) => x,
243 +
            Bound::Excluded(&x) if x > T::MIN => x - T::ONE,
244 +
            Bound::Excluded(_) => panic!(
245 +
                "Uniform::from_range: empty range {:?}..{:?}",
246 +
                range.start_bound(),
247 +
                range.end_bound()
248 +
            ),
249 +
        };
250 +
        assert!(
251 +
            low <= high,
252 +
            "Uniform::from_range: empty range {:?}..{:?}",
253 +
            range.start_bound(),
254 +
            range.end_bound()
255 +
        );
256 +
        Self { low, high }
257 +
    }
258 +
}
259 +
260 +
impl<T> Distribution<T> for Uniform<T>
261 +
where
262 +
    T: Copy + PartialOrd + Integer,
263 +
{
264 +
    fn sample<R: Entropy>(&self, rng: &mut R) -> T {
265 +
        let low = self.low;
266 +
        let high = self.high;
267 +
268 +
        if low == T::MIN && high == T::MAX {
269 +
            return T::from_u64(rng.gen_u64());
270 +
        }
271 +
272 +
        let len = high.wrapping_sub(low).as_u64() + 1;
273 +
        let threshold = len.wrapping_neg() % len;
274 +
        loop {
275 +
            let value = rng.gen_u64();
276 +
            if value >= threshold {
277 +
                return low.wrapping_add(T::from_u64(value % len));
278 +
            }
279 +
        }
280 +
    }
281 +
}
282 +
283 +
#[cfg(test)]
284 +
mod tests {
285 +
    use super::*;
286 +
    use crate::math::traits::Integer;
287 +
288 +
    struct SequenceEntropy {
289 +
        values: std::vec::IntoIter<u64>,
290 +
    }
291 +
292 +
    impl SequenceEntropy {
293 +
        fn new(values: Vec<u64>) -> Self {
294 +
            Self {
295 +
                values: values.into_iter(),
296 +
            }
297 +
        }
298 +
    }
299 +
300 +
    impl Entropy for SequenceEntropy {
301 +
        fn gen_u64(&mut self) -> u64 {
302 +
            self.values.next().unwrap()
303 +
        }
304 +
    }
305 +
306 +
    #[allow(dead_code)]
307 +
    fn distribution<T: Integer + std::fmt::Debug>(
308 +
        rng: &mut Rng,
309 +
        range: std::ops::Range<T>,
310 +
        samples: usize,
311 +
        buckets: usize,
312 +
    ) {
313 +
        let mut counts = vec![0; buckets];
314 +
        let bucket_size = (range.end - range.start).as_u64() as f64 / buckets as f64;
315 +
316 +
        for _ in 0..samples {
317 +
            let value = rng.generate(range.clone());
318 +
            let bucket = ((value - range.start).as_u64() as f64 / bucket_size) as usize;
319 +
            counts[bucket.min(buckets - 1)] += 1;
320 +
        }
321 +
322 +
        let expected = samples as f64 / buckets as f64;
323 +
        for (i, &count) in counts.iter().enumerate() {
324 +
            let deviation = (count as f64 - expected).abs() / expected * 100.0;
325 +
            println!("Bucket {}: {} ({:.1}% deviation)", i, count, deviation);
326 +
        }
327 +
    }
328 +
329 +
    fn distribution_f64(rng: &mut Rng, samples: usize, buckets: usize) {
330 +
        let mut counts = vec![0; buckets];
331 +
        let bucket_size = 1.0 / buckets as f64;
332 +
333 +
        for _ in 0..samples {
334 +
            let value = rng.fraction();
335 +
            let bucket = (value / bucket_size) as usize;
336 +
            counts[bucket.min(buckets - 1)] += 1;
337 +
        }
338 +
339 +
        let expected = samples as f64 / buckets as f64;
340 +
        for (i, &count) in counts.iter().enumerate() {
341 +
            let deviation = (count as f64 - expected).abs() / expected * 100.0;
342 +
            println!("Bucket {}: {} ({:.1}% deviation)", i, count, deviation);
343 +
        }
344 +
    }
345 +
346 +
    #[test]
347 +
    fn fraction_is_less_than_one() {
348 +
        let mut rng = Rng::with_seed(0);
349 +
        rng.state = 0x6fa8_99d2_ddf8_ba1d;
350 +
351 +
        assert!(rng.fraction() < 1.0);
352 +
    }
353 +
354 +
    #[test]
355 +
    fn full_i32_distribution_preserves_signed_bits() {
356 +
        let distribution = Uniform::<i32>::full();
357 +
        let mut rng = SequenceEntropy::new(vec![u64::MAX]);
358 +
359 +
        assert_eq!(distribution.sample(&mut rng), -1);
360 +
    }
361 +
362 +
    #[test]
363 +
    fn bounded_distribution_rejects_biased_prefix() {
364 +
        let distribution = Uniform::new(0_u64, 2);
365 +
        let mut rng = SequenceEntropy::new(vec![0, 2]);
366 +
367 +
        assert_eq!(distribution.sample(&mut rng), 2);
368 +
    }
369 +
370 +
    #[test]
371 +
    fn test_distribution() {
372 +
        let mut rng = Rng::new();
373 +
374 +
        distribution_f64(&mut rng, 100000, 10);
375 +
    }
376 +
377 +
    #[test]
378 +
    fn test_basic_generation() {
379 +
        let mut rng = Rng::new();
380 +
381 +
        // Using gen
382 +
        let _: u64 = rng.generate(..);
383 +
        let _: bool = rng.flip();
384 +
385 +
        // Using gen_range
386 +
        let n = rng.generate(1u64..=100);
387 +
        assert!((1..=100).contains(&n));
388 +
389 +
        for _ in 0..10 {
390 +
            let n = rng.generate(0..60);
391 +
            assert!((0..60).contains(&n), "{n}");
392 +
        }
393 +
    }
394 +
395 +
    #[test]
396 +
    fn test_fill_bytes() {
397 +
        let mut rng = Rng::with_seed(49182);
398 +
399 +
        // Test different buffer sizes
400 +
        let sizes = [1, 7, 8, 9, 16, 32, 64];
401 +
        for size in sizes {
402 +
            let mut buffer = vec![0u8; size];
403 +
            rng.fill(&mut buffer);
404 +
405 +
            // Ensure we actually wrote some non-zero bytes
406 +
            assert!(
407 +
                buffer.iter().any(|&x| x != 0),
408 +
                "Buffer of size {} contains only zeros",
409 +
                size
410 +
            );
411 +
        }
412 +
413 +
        // Test alignment handling
414 +
        let mut buffer = [0u8; 32];
415 +
        rng.fill(&mut buffer[1..31]); // Unaligned slice
416 +
    }
417 +
418 +
    #[test]
419 +
    fn test_seeded_sequences() {
420 +
        let mut rng1 = Rng::with_seed(12345);
421 +
        let mut rng2 = Rng::with_seed(12345);
422 +
423 +
        // Same seed should produce same sequence
424 +
        for _ in 0..100 {
425 +
            assert_eq!(rng1.gen_u64(), rng2.gen_u64());
426 +
        }
427 +
428 +
        // Different seeds should produce different sequences
429 +
        let mut rng3 = Rng::with_seed(12346);
430 +
        let val1 = rng1.gen_u64();
431 +
        let val2 = rng3.gen_u64();
432 +
        assert_ne!(val1, val2);
433 +
    }
434 +
435 +
    #[test]
436 +
    fn test_shuffle() {
437 +
        let mut rng = Rng::new();
438 +
439 +
        // Test with different sizes
440 +
        for len in [2, 3, 10, 100] {
441 +
            let mut v: Vec<i32> = (0..len).collect();
442 +
            let original = v.clone();
443 +
444 +
            rng.shuffle(&mut v);
445 +
446 +
            // Length should remain the same
447 +
            assert_eq!(v.len(), original.len());
448 +
449 +
            // All elements should still be present
450 +
            assert!(v.iter().all(|x| original.contains(x)));
451 +
452 +
            // Order should be different (for large enough arrays)
453 +
            if len > 10 {
454 +
                assert_ne!(v, original);
455 +
            }
456 +
        }
457 +
458 +
        // Test empty and single-element slices
459 +
        let mut empty: Vec<i32> = vec![];
460 +
        rng.shuffle(&mut empty);
461 +
        assert!(empty.is_empty());
462 +
463 +
        let mut single = vec![1];
464 +
        rng.shuffle(&mut single);
465 +
        assert_eq!(single, vec![1]);
466 +
    }
467 +
468 +
    #[test]
469 +
    fn test_consecutive_values() {
470 +
        let mut rng = Rng::new();
471 +
        let mut prev = rng.gen_u64();
472 +
        let mut repeats = 0;
473 +
474 +
        // Test for obvious patterns in consecutive values
475 +
        for _ in 0..1000 {
476 +
            let curr = rng.gen_u64();
477 +
            if curr == prev {
478 +
                repeats += 1;
479 +
            }
480 +
            prev = curr;
481 +
        }
482 +
483 +
        // Shouldn't have too many repeats
484 +
        assert!(repeats < 3, "Too many repeated consecutive values");
485 +
    }
486 +
}