| 1 |
// Test that a custom handler works on wasm32-unknown-unknown |
| 2 |
#![cfg(all( |
| 3 |
target_arch = "wasm32", |
| 4 |
target_os = "unknown", |
| 5 |
feature = "custom", |
| 6 |
not(feature = "js") |
| 7 |
))] |
| 8 |
|
| 9 |
use wasm_bindgen_test::wasm_bindgen_test as test; |
| 10 |
|
| 11 |
use core::num::NonZeroU32; |
| 12 |
use getrandom::{getrandom, register_custom_getrandom, Error}; |
| 13 |
|
| 14 |
fn len7_err() -> Error { |
| 15 |
NonZeroU32::new(Error::INTERNAL_START + 7).unwrap().into() |
| 16 |
} |
| 17 |
|
| 18 |
fn super_insecure_rng(buf: &mut [u8]) -> Result<(), Error> { |
| 19 |
// `getrandom` guarantees it will not call any implementation if the output |
| 20 |
// buffer is empty. |
| 21 |
assert!(!buf.is_empty()); |
| 22 |
// Length 7 buffers return a custom error |
| 23 |
if buf.len() == 7 { |
| 24 |
return Err(len7_err()); |
| 25 |
} |
| 26 |
// Otherwise, fill bytes based on input length |
| 27 |
let mut start = buf.len() as u8; |
| 28 |
for b in buf { |
| 29 |
*b = start; |
| 30 |
start = start.wrapping_mul(3); |
| 31 |
} |
| 32 |
Ok(()) |
| 33 |
} |
| 34 |
|
| 35 |
register_custom_getrandom!(super_insecure_rng); |
| 36 |
|
| 37 |
use getrandom::getrandom as getrandom_impl; |
| 38 |
mod common; |
| 39 |
|
| 40 |
#[test] |
| 41 |
fn custom_rng_output() { |
| 42 |
let mut buf = [0u8; 4]; |
| 43 |
assert_eq!(getrandom(&mut buf), Ok(())); |
| 44 |
assert_eq!(buf, [4, 12, 36, 108]); |
| 45 |
|
| 46 |
let mut buf = [0u8; 3]; |
| 47 |
assert_eq!(getrandom(&mut buf), Ok(())); |
| 48 |
assert_eq!(buf, [3, 9, 27]); |
| 49 |
} |
| 50 |
|
| 51 |
#[test] |
| 52 |
fn rng_err_output() { |
| 53 |
assert_eq!(getrandom(&mut [0; 7]), Err(len7_err())); |
| 54 |
} |