• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015-2019 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10 // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 
15 use ring::{
16     rand::{self, SecureRandom as _},
17     test,
18 };
19 
20 #[cfg(target_arch = "wasm32")]
21 use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure};
22 
23 #[cfg(target_arch = "wasm32")]
24 wasm_bindgen_test_configure!(run_in_browser);
25 
26 #[test]
27 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
test_system_random_lengths()28 fn test_system_random_lengths() {
29     const LINUX_LIMIT: usize = 256;
30     const WEB_LIMIT: usize = 65536;
31 
32     // Test that `fill` succeeds for various interesting lengths. `256` and
33     // multiples thereof are interesting because that's an edge case for
34     // `getrandom` on Linux.
35     let lengths = [
36         0,
37         1,
38         2,
39         3,
40         96,
41         LINUX_LIMIT - 1,
42         LINUX_LIMIT,
43         LINUX_LIMIT + 1,
44         LINUX_LIMIT * 2,
45         511,
46         512,
47         513,
48         4096,
49         WEB_LIMIT - 1,
50         WEB_LIMIT,
51         WEB_LIMIT + 1,
52         WEB_LIMIT * 2,
53     ];
54 
55     for len in lengths.iter() {
56         let mut buf = vec![0; *len];
57 
58         let rng = rand::SystemRandom::new();
59         assert!(rng.fill(&mut buf).is_ok());
60 
61         // If `len` < 96 then there's a big chance of false positives, but
62         // otherwise the likelihood of a false positive is so too low to
63         // worry about.
64         if *len >= 96 {
65             assert!(buf.iter().any(|x| *x != 0));
66         }
67     }
68 }
69 
70 #[test]
71 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
test_system_random_traits()72 fn test_system_random_traits() {
73     test::compile_time_assert_clone::<rand::SystemRandom>();
74     test::compile_time_assert_send::<rand::SystemRandom>();
75 
76     assert_eq!(
77         "SystemRandom(())",
78         format!("{:?}", rand::SystemRandom::new())
79     );
80 }
81