mc_rand/
lib.rs

1// Copyright (c) 2018-2023 The MobileCoin Foundation
2
3#![no_std]
4#![doc = include_str!("../README.md")]
5
6pub extern crate rand_core;
7
8pub use rand_core::{CryptoRng, RngCore};
9
10use cfg_if::cfg_if;
11
12// Not using cfg_attr( ..., path = fallback.rs) because it appears to confuse
13// rustfmt
14cfg_if! {
15    if #[cfg(target_feature = "rdrand")] {
16        mod rdrandrng;
17        pub use rdrandrng::McRng;
18    } else if #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] {
19        mod wasm;
20        pub use wasm::McRng;
21    } else {
22        mod fallback;
23        pub use fallback::McRng;
24    }
25}
26
27#[cfg(test)]
28mod test {
29    use super::*;
30
31    #[test]
32    fn test_entropy_32() {
33        let first_result = McRng::default().next_u32();
34        for _ in 0..50 {
35            let result = McRng::default().next_u32();
36            if result != first_result {
37                return;
38            }
39        }
40        panic!("Got the same u32 50 times in a row: {}", first_result);
41    }
42
43    #[test]
44    fn test_entropy_64() {
45        let first_result = McRng::default().next_u64();
46        for _ in 0..50 {
47            let result = McRng::default().next_u64();
48            if result != first_result {
49                return;
50            }
51        }
52        panic!("Got the same u64 50 times in a row: {}", first_result);
53    }
54
55    #[test]
56    fn test_not_filled() {
57        let result = McRng::default().next_u32();
58        if result == 0 || result == 0xFFFF_FFFFu32 {
59            panic!("Result should never be 0 or 0xFFFFFFFFu32");
60        }
61        let result = McRng::default().next_u64();
62        if result == 0 || result == 0xFFFF_FFFF_FFFF_FFFFu64 {
63            panic!("Result should never be 0 or 0xFFFFFFFFFFFFFFFFu64");
64        }
65    }
66}