1use getrandom::getrandom;
4use rand_core::{CryptoRng, RngCore};
5use crate::traits::AllowedRng;
6
7pub struct WasmRng;
9
10impl CryptoRng for WasmRng {}
11
12impl RngCore for WasmRng {
13 fn next_u32(&mut self) -> u32 {
14 let mut bytes = [0u8; 4];
15 self.fill_bytes(&mut bytes);
16 u32::from_le_bytes(bytes)
17 }
18
19 fn next_u64(&mut self) -> u64 {
20 let mut bytes = [0u8; 8];
21 self.fill_bytes(&mut bytes);
22 u64::from_le_bytes(bytes)
23 }
24
25 fn fill_bytes(&mut self, dest: &mut [u8]) {
26 getrandom(dest).expect("getrandom failed in browser environment");
27 }
28
29 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
30 self.fill_bytes(dest);
33 Ok(())
34 }
35}
36
37impl AllowedRng for WasmRng {}
38
39impl Default for WasmRng {
40 fn default() -> Self {
41 Self
42 }
43}
44
45pub type WasmRngFromSeed = rand_chacha::ChaCha20Rng;
47
48