Skip to content

Commit 8863931

Browse files
committed
Add quality tests for calling getrandom on small buffers
Signed-off-by: Joe Richey <joerichey@google.com>
1 parent a9dd25c commit 8863931

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

tests/common/mod.rs

+25
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ fn test_zero() {
1313
}
1414

1515
// Return the number of bits in which s1 and s2 differ
16+
#[cfg(not(feature = "custom"))]
1617
fn num_diff_bits(s1: &[u8], s2: &[u8]) -> usize {
1718
assert_eq!(s1.len(), s2.len());
1819
let mut n = 0;
@@ -39,6 +40,30 @@ fn test_diff() {
3940
assert!(d < 4500);
4041
}
4142

43+
// Tests the quality of calling getrandom repeatedly on small buffers
44+
#[test]
45+
#[cfg(not(feature = "custom"))]
46+
fn test_small() {
47+
// For each buffer size, get at least 256 bytes and check that between
48+
// 3 and 5 bits per byte differ. Probability of failure:
49+
// ~ 2^(-91) = 64 * 2 * CDF[BinomialDistribution[8*256, 0.5], 3*256]
50+
for size in 1..=64 {
51+
let mut num_bytes = 0;
52+
let mut diff_bits = 0;
53+
while num_bytes < 256 {
54+
let mut s1 = vec![0u8; size];
55+
getrandom_impl(&mut s1).unwrap();
56+
let mut s2 = vec![0u8; size];
57+
getrandom_impl(&mut s2).unwrap();
58+
59+
num_bytes += size;
60+
diff_bits += num_diff_bits(&s1, &s2);
61+
}
62+
assert!(diff_bits > 3 * num_bytes);
63+
assert!(diff_bits < 5 * num_bytes);
64+
}
65+
}
66+
4267
#[test]
4368
fn test_huge() {
4469
let mut huge = [0u8; 100_000];

0 commit comments

Comments
 (0)