Debian Codegraph @

third_party/rust/rust_decimal/src/rand.rs

raw
1 use crate::Decimal;
2 use rand::{
3 distributions::{
4 uniform::{SampleBorrow, SampleUniform, UniformInt, UniformSampler},
5 Distribution, Standard,
6 },
7 Rng,
8 };
9
10 impl Distribution<Decimal> for Standard {
11 fn sample<R>(&self, rng: &mut R) -> Decimal
12 where
13 R: Rng + ?Sized,
14 {
15 Decimal::from_parts(
16 rng.next_u32(),
17 rng.next_u32(),
18 rng.next_u32(),
19 rng.gen(),
20 rng.next_u32(),
21 )
22 }
23 }
24
25 impl SampleUniform for Decimal {
26 type Sampler = DecimalSampler;
27 }
28
29 #[derive(Clone, Copy, Debug, PartialEq)]
30 pub struct DecimalSampler {
31 mantissa_sampler: UniformInt<i128>,
32 scale: u32,
33 }
34
35 impl UniformSampler for DecimalSampler {
36 type X = Decimal;
37
38 /// Creates a new sampler that will yield random decimal objects between `low` and `high`.
39 ///
40 /// The sampler will always provide decimals at the same scale as the inputs; if the inputs
41 /// have different scales, the higher scale is used.
42 ///
43 /// # Example
44 ///
45 /// ```
46 /// # use rand::Rng;
47 /// # use rust_decimal_macros::dec;
48 /// let mut rng = rand::rngs::OsRng;
49 /// let random = rng.gen_range(dec!(1.00)..dec!(2.00));
50 /// assert!(random >= dec!(1.00));
51 /// assert!(random < dec!(2.00));
52 /// assert_eq!(random.scale(), 2);
53 /// ```
54 #[inline]
55 fn new<B1, B2>(low: B1, high: B2) -> Self
56 where
57 B1: SampleBorrow<Self::X> + Sized,
58 B2: SampleBorrow<Self::X> + Sized,
59 {
60 let (low, high) = sync_scales(*low.borrow(), *high.borrow());
61 let high = Decimal::from_i128_with_scale(high.mantissa() - 1, high.scale());
62 UniformSampler::new_inclusive(low, high)
63 }
64
65 /// Creates a new sampler that will yield random decimal objects between `low` and `high`.
66 ///
67 /// The sampler will always provide decimals at the same scale as the inputs; if the inputs
68 /// have different scales, the higher scale is used.
69 ///
70 /// # Example
71 ///
72 /// ```
73 /// # use rand::Rng;
74 /// # use rust_decimal_macros::dec;
75 /// let mut rng = rand::rngs::OsRng;
76 /// let random = rng.gen_range(dec!(1.00)..=dec!(2.00));
77 /// assert!(random >= dec!(1.00));
78 /// assert!(random <= dec!(2.00));
79 /// assert_eq!(random.scale(), 2);
80 /// ```
81 #[inline]
82 fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self
83 where
84 B1: SampleBorrow<Self::X> + Sized,
85 B2: SampleBorrow<Self::X> + Sized,
86 {
87 let (low, high) = sync_scales(*low.borrow(), *high.borrow());
88
89 // Return our sampler, which contains an underlying i128 sampler so we
90 // outsource the actual randomness implementation.
91 Self {
92 mantissa_sampler: UniformInt::new_inclusive(low.mantissa(), high.mantissa()),
93 scale: low.scale(),
94 }
95 }
96
97 #[inline]
98 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
99 let mantissa = self.mantissa_sampler.sample(rng);
100 Decimal::from_i128_with_scale(mantissa, self.scale)
101 }
102 }
103
104 /// Return equivalent Decimal objects with the same scale as one another.
105 #[inline]
106 fn sync_scales(mut a: Decimal, mut b: Decimal) -> (Decimal, Decimal) {
107 if a.scale() == b.scale() {
108 return (a, b);
109 }
110
111 // Set scales to match one another, because we are relying on mantissas'
112 // being comparable in order outsource the actual sampling implementation.
113 a.rescale(a.scale().max(b.scale()));
114 b.rescale(a.scale().max(b.scale()));
115
116 // Edge case: If the values have _wildly_ different scales, the values may not have rescaled far enough to match one another.
117 //
118 // In this case, we accept some precision loss because the randomization approach we are using assumes that the scales will necessarily match.
119 if a.scale() != b.scale() {
120 a.rescale(a.scale().min(b.scale()));
121 b.rescale(a.scale().min(b.scale()));
122 }
123
124 (a, b)
125 }
126
127 #[cfg(test)]
128 mod tests {
129 use std::collections::HashSet;
130
131 use super::*;
132
133 macro_rules! dec {
134 ($e:expr) => {
135 Decimal::from_str_exact(stringify!($e)).unwrap()
136 };
137 }
138
139 #[test]
140 fn has_random_decimal_instances() {
141 let mut rng = rand::rngs::OsRng;
142 let random: [Decimal; 32] = rng.gen();
143 assert!(random.windows(2).any(|slice| { slice[0] != slice[1] }));
144 }
145
146 #[test]
147 fn generates_within_range() {
148 let mut rng = rand::rngs::OsRng;
149 for _ in 0..128 {
150 let random = rng.gen_range(dec!(1.00)..dec!(1.05));
151 assert!(random < dec!(1.05));
152 assert!(random >= dec!(1.00));
153 }
154 }
155
156 #[test]
157 fn generates_within_inclusive_range() {
158 let mut rng = rand::rngs::OsRng;
159 let mut values: HashSet<Decimal> = HashSet::new();
160 for _ in 0..256 {
161 let random = rng.gen_range(dec!(1.00)..=dec!(1.01));
162 // The scale is 2, so 1.00 and 1.01 are the only two valid choices.
163 assert!(random == dec!(1.00) || random == dec!(1.01));
164 values.insert(random);
165 }
166 // Somewhat flaky, will fail 1 out of every 2^255 times this is run.
167 // Probably acceptable in the real world.
168 assert_eq!(values.len(), 2);
169 }
170
171 #[test]
172 fn test_edge_case_scales_match() {
173 let (low, high) = sync_scales(dec!(1.000_000_000_000_000_000_01), dec!(100_000_000_000_000_000_001));
174 assert_eq!(low.scale(), high.scale());
175 }
176 }