Debian Codegraph @

src/lib.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 #![no_std]
2 #![recursion_limit = "130"]
3 #![deny(missing_docs)]
4 #![cfg_attr(test, deny(warnings))]
5
6 //! # Random Trait
7 //!
8 //! This crate provides a simple thin trait for producing generic random values based on any random source.
9 //! The crates assurances are based on the assurances of the RNG it is implemented on.<br>
10 //! if that RNG is cryptographically secure then this crate should provide a cryptographically secure numbers. (including floats)
11 //! if the RNG is biased (which is fine for tests and some other applications) then the results will also be bias.
12 //! This crate **does not** try to compensate for biases in the RNG source.
13 //!
14 //! please see the [`GenerateRand`](trait.GenerateRand.html) and [`Random`](trait.Random.html) for more information and examples.
15 //!
16
17 use core::{char, mem};
18
19 /// This trait is used by `Random::gen()` as a generic function to create a random value for any type which implements it.
20 /// I try to give by default implementations for all the types in libcore, including arrays and tuples, if anything is missing please raise the issue.
21 /// You can implement this for any of your types.
22 /// # Examples
23 /// ```rust
24 /// use random_trait::{Random, GenerateRand};
25 /// struct MyStuff{
26 /// a: u64,
27 /// b: char,
28 /// }
29 ///
30 /// impl GenerateRand for MyStuff {
31 /// fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
32 /// MyStuff {a: rand.gen(), b: rand.gen() }
33 /// }
34 /// }
35 /// ```
36 ///
37 pub trait GenerateRand {
38 /// Generate a random value, using the `rand` as source of randomness.
39 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self;
40 }
41
42 ///
43 /// This is the base trait of the crate. By implementing the required method on your random generator source
44 /// it will give you a long list of functions, the important of them is `Random::gen() -> T` which will produce a random value
45 /// for every type which implements `GenerateRand` (you can implement this for your own types).
46 ///
47 /// Notice that some random sources can produce non byte-array values with more efficiency, so if you want to use that
48 /// you can just override a provided method and use the random source directly.
49 ///
50 /// If your random source is fallable in a way that can be handled please also implement `fill_bytes` and handle the errors properly.
51 /// otherwise it will panic.
52 ///
53 /// # Example
54 /// ```rust
55 /// use random_trait::{Random, GenerateRand};
56 ///
57 /// #[derive(Default)]
58 /// struct MyRandomGenerator {
59 /// ctr: usize,
60 /// }
61 ///
62 /// impl Random for MyRandomGenerator {
63 /// type Error = ();
64 /// fn try_fill_bytes(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
65 /// for e in buf.iter_mut() {
66 /// *e = self.ctr as u8;
67 /// self.ctr += 1;
68 /// }
69 /// Ok(())
70 /// }
71 /// }
72 ///
73 /// # fn main() {
74 /// let mut rand = MyRandomGenerator::default();
75 /// let rand_u32: u32 = rand.gen();
76 /// assert_eq!(rand_u32, 50462976);
77 /// let rand_u32: u32 = rand.gen();
78 /// assert_eq!(rand_u32, 117835012);
79 /// # }
80 /// ```
81 ///
82 pub trait Random {
83 /// The Error type, based on the source of randomness, non fallible sources can use `Error=()`
84 type Error;
85
86 /// This is the main method of the trait.
87 /// You should implement this on your randomness source and will the buffer with random data.
88 fn try_fill_bytes(&mut self, buf: &mut [u8]) -> Result<(), Self::Error>;
89
90 /// Uses `try_fill_bytes` but panics if returns an error.
91 /// Override if you can gracefully handle errors in the randomness source.
92 fn fill_bytes(&mut self, buf: &mut [u8]) {
93 if self.try_fill_bytes(buf).is_err() {
94 panic!("Failed getting randmness");
95 }
96 }
97
98 /// Returns a generic random value which implements `GenerateRand`
99 fn gen<T: GenerateRand>(&mut self) -> T {
100 T::generate(self)
101 }
102
103 /// Returns a random `u8` number.
104 fn get_u8(&mut self) -> u8 {
105 let mut buf = [0u8; 1];
106 self.fill_bytes(&mut buf);
107 buf[0]
108 }
109
110 /// Returns a random `u16` number.
111 fn get_u16(&mut self) -> u16 {
112 let mut buf = [0u8; 2];
113 self.fill_bytes(&mut buf);
114 unsafe { mem::transmute(buf) }
115 }
116
117 /// Returns a random `u32` number.
118 fn get_u32(&mut self) -> u32 {
119 let mut buf = [0u8; 4];
120 self.fill_bytes(&mut buf);
121 unsafe { mem::transmute(buf) }
122 }
123
124 /// Returns a random `u64` number.
125 fn get_u64(&mut self) -> u64 {
126 let mut buf = [0u8; 8];
127 self.fill_bytes(&mut buf);
128 unsafe { mem::transmute(buf) }
129 }
130
131 /// Returns a random `usize` number.
132 #[cfg(target_pointer_width = "64")]
133 fn get_usize(&mut self) -> usize {
134 self.get_u64() as usize
135 }
136
137 /// Returns a random `usize` number.
138 #[cfg(target_pointer_width = "32")]
139 fn get_usize(&mut self) -> usize {
140 self.get_u32() as usize
141 }
142
143 /// Returns a random `usize` number.
144 #[cfg(target_pointer_width = "16")]
145 fn get_usize(&mut self) -> usize {
146 self.get_u16() as usize
147 }
148
149 /// Returns a random `u128` number.
150 #[cfg(feature = "u128")]
151 fn get_u128(&mut self) -> u128 {
152 let mut buf = [0u8; 16];
153 self.fill_bytes(&mut buf);
154 unsafe { mem::transmute(buf) }
155 }
156
157 /// Returns a random `bool` with 50/50 probability.
158 fn get_bool(&mut self) -> bool {
159 // TODO: More research, least/most significant bit?
160 let bit = self.get_u8() & 0b1000_0000;
161 debug_assert!(bit < 2);
162 bit == 1
163 }
164 }
165
166 impl GenerateRand for u8 {
167 #[inline]
168 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
169 rand.get_u8()
170 }
171 }
172
173 impl GenerateRand for u16 {
174 #[inline]
175 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
176 rand.get_u16()
177 }
178 }
179
180 impl GenerateRand for u32 {
181 #[inline]
182 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
183 rand.get_u32()
184 }
185 }
186
187 impl GenerateRand for u64 {
188 #[inline]
189 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
190 rand.get_u64()
191 }
192 }
193
194 impl GenerateRand for usize {
195 #[inline]
196 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
197 rand.get_usize()
198 }
199 }
200
201 #[cfg(feature = "u128")]
202 impl GenerateRand for u128 {
203 #[inline]
204 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
205 rand.get_u128()
206 }
207 }
208
209 impl GenerateRand for char {
210 #[inline]
211 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
212 loop {
213 if let Some(c) = char::from_u32(rand.get_u32()) {
214 return c;
215 }
216 }
217 }
218 }
219
220 impl GenerateRand for bool {
221 #[inline]
222 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
223 rand.get_bool()
224 }
225 }
226
227 // Source: https://mumble.net/~campbell/2014/04/28/uniform-random-float
228 // https://mumble.net/~campbell/2014/04/28/random_real.c
229 impl GenerateRand for f64 {
230 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
231 let mut exponent: i32 = -64;
232 let mut significand = rand.get_u64();
233 while significand == 0 {
234 exponent -= 64;
235 if exponent < -1074i32 {
236 // E min(-1022)-p(53)+1 (https://en.wikipedia.org/wiki/IEEE_754)
237 // In reallity this should probably never happen. prob of ~1/(2^1024) unless randomness is broken.
238 unreachable!("The randomness is broken, got 0 16 times. (prob of 1/2^1024)");
239 }
240 significand = rand.get_u64();
241 }
242
243 // Shift the leading zeros into the exponent
244 let shift = significand.leading_zeros() as i32;
245 if shift > 0 {
246 exponent -= shift;
247 significand <<= shift;
248 significand |= rand.get_u64() >> (64 - shift);
249 }
250 // Set the sticky bit.
251 significand |= 1;
252
253 // Convert to float and scale by 2^exponent.
254 significand as f64 * exp2(exponent)
255 }
256 }
257
258 // Source: https://mumble.net/~campbell/2014/04/28/uniform-random-float
259 // https://mumble.net/~campbell/2014/04/28/random_real.c
260 impl GenerateRand for f32 {
261 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
262 let mut exponent: i32 = -32;
263 let mut significand = rand.get_u32();
264 while significand == 0 {
265 exponent -= 32;
266 if exponent < -149i32 {
267 // E min(-126)-p(24)+1 (https://en.wikipedia.org/wiki/IEEE_754)
268 // In reallity this should probably never happen. prob of ~1/(2^1024) unless randomness is broken.
269 unreachable!("The randomness is broken, got 0 5 times. (prob of 1/2^160)");
270 // TODO: Should this stay unreachable or change to return 0?
271 }
272 significand = rand.get_u32();
273 }
274
275 // Shift the leading zeros into the exponent
276 let shift = significand.leading_zeros() as i32;
277 if shift != 0 {
278 exponent -= shift;
279 significand <<= shift;
280 significand |= rand.get_u32() >> (32 - shift);
281 }
282 // Set the sticky bit, almost definitely another 1 in the random stream.
283 significand |= 1;
284
285 // Convert to float and scale by 2^exponent.
286 significand as f32 * exp2f(exponent)
287 }
288 }
289
290 /// This is from IEEE-754.
291 /// you take the E max, subtract the exponent from it, and shift it according to the precision-1
292 fn exp2f(exp: i32) -> f32 {
293 debug_assert!(exp > -127);
294 let bits = ((127i32 + exp) as u32) << 23u32;
295 unsafe { mem::transmute(bits) } // this is the same as `f32::from_bits`
296 }
297 fn exp2(exp: i32) -> f64 {
298 debug_assert!(exp > -1023);
299 let bits = ((1023i32 + exp) as u64) << 52u64;
300 unsafe { mem::transmute(bits) } // this is the same as `f64::from_bits`
301 }
302
303 // Will overflow(i.e. sign extend) correctly https://doc.rust-lang.org/nomicon/casts.html.
304 // should only be used with the same type.
305 macro_rules! impl_generate_rand_ifromu {
306 ($ity:ty, $uty: ty) => {
307 impl GenerateRand for $ity {
308 #[inline]
309 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
310 debug_assert_eq!(mem::size_of::<$ity>(), mem::size_of::<$uty>());
311 <$uty>::generate(rand) as $ity
312 }
313 }
314 };
315 }
316
317 impl_generate_rand_ifromu! {i8, u8}
318 impl_generate_rand_ifromu! {i16, u16}
319 impl_generate_rand_ifromu! {i32, u32}
320 impl_generate_rand_ifromu! {i64, u64}
321 impl_generate_rand_ifromu! {isize, usize}
322 #[cfg(feature = "u128")]
323 impl_generate_rand_ifromu! {i128, u128}
324
325 // the reason for both $t and $ts is that this way each iteration it's reducing the amount of variables by one
326 macro_rules! array_impls {
327 {$N:expr, $t:ident $($ts:ident)*} => {
328 impl<T: GenerateRand> GenerateRand for [T; $N] {
329 #[inline]
330 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
331 [rand.gen::<$t>(), $(rand.gen::<$ts>()),*]
332 }
333 }
334 array_impls!{($N - 1), $($ts)*}
335 };
336 {$N:expr,} => {
337 impl<T: GenerateRand> GenerateRand for [T; $N] {
338 #[inline]
339 fn generate<R: Random + ?Sized>(_: &mut R) -> Self { [] }
340 }
341 };
342 }
343
344 array_impls! {128, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T
345 T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T}
346
347 macro_rules! tuple_impls {
348 ($(
349 ($($T:ident),+),
350 )+) => {
351 $(
352 impl<$($T: GenerateRand),+> GenerateRand for ($($T,)+) {
353 #[inline]
354 fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
355 ($({ let x: $T = rand.gen(); x},)+)
356 }
357 }
358 )+
359 }
360 }
361
362 tuple_impls! {
363 (A),
364 (A, B),
365 (A, B, C),
366 (A, B, C, D),
367 (A, B, C, D, E),
368 (A, B, C, D, E, F),
369 (A, B, C, D, E, F, G),
370 (A, B, C, D, E, F, G, H),
371 (A, B, C, D, E, F, G, H, I),
372 (A, B, C, D, E, F, G, H, I, J),
373 (A, B, C, D, E, F, G, H, I, J, K),
374 (A, B, C, D, E, F, G, H, I, J, K, L),
375 (A, B, C, D, E, F, G, H, I, J, K, L, M),
376 (A, B, C, D, E, F, G, H, I, J, K, L, M, N),
377 (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O),
378 (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P),
379 }