-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathrng.rs
More file actions
88 lines (77 loc) · 2.17 KB
/
rng.rs
File metadata and controls
88 lines (77 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* SPDX-License-Identifier: MIT
* Copyright (c) 2023 - 2026. The DeepCausality Authors and Contributors. All Rights Reserved.
*/
use crate::{Distribution, Fill, RngCore, SampleRange, SampleUniform};
use crate::{Iter, Map, StandardUniform};
impl<T: Rng> Rng for &mut T {}
pub trait Rng: RngCore {
#[inline]
fn random<T>(&mut self) -> T
where
StandardUniform: Distribution<T>,
{
StandardUniform.sample(self)
}
#[inline]
fn random_iter<T>(&mut self) -> Iter<StandardUniform, &mut Self, T>
where
Self: Sized,
StandardUniform: Distribution<T>,
{
StandardUniform.sample_iter(self)
}
#[track_caller]
fn random_range<T, R>(&mut self, range: R) -> T
where
T: SampleUniform,
R: SampleRange<T>,
{
assert!(!range.is_empty(), "cannot sample empty range");
range.sample_single(self).unwrap()
}
#[inline]
#[track_caller]
fn random_bool(&mut self, p: f64) -> bool {
if !(0.0..=1.0).contains(&p) {
panic!("p={} is outside range [0.0, 1.0]", p);
}
self.next_u64() as f64 / (u64::MAX as f64) <= p
}
#[inline]
#[track_caller]
fn random_ratio(&mut self, numerator: u32, denominator: u32) -> bool {
if denominator == 0 || numerator > denominator {
panic!(
"p={}/{} is outside range [0.0, 1.0]",
numerator, denominator
);
}
self.next_u64() % (denominator as u64) < (numerator as u64)
}
fn sample<T, D: Distribution<T>>(&mut self, distr: D) -> T {
distr.sample(self)
}
fn sample_iter<T, D>(&mut self, distr: D) -> Iter<D, &mut Self, T>
where
D: Distribution<T>,
Self: Sized,
{
distr.sample_iter(self)
}
#[track_caller]
fn fill<T: Fill + ?Sized>(&mut self, dest: &mut T) {
dest.fill(self)
}
fn map<T, S, F>(&mut self, func: F) -> Map<StandardUniform, F, T, S>
where
StandardUniform: Distribution<T>,
F: Fn(T) -> S,
{
Map {
distr: StandardUniform,
func,
phantom: core::marker::PhantomData,
}
}
}