Debian Codegraph @

third_party/rust/getrandom/src/backends/wasi_p2.rs

raw
1 //! Implementation for WASI Preview 2.
2 use crate::Error;
3 use core::mem::MaybeUninit;
4 use wasi::random::random::get_random_u64;
5
6 #[inline]
7 pub fn inner_u32() -> Result<u32, Error> {
8 let val = get_random_u64();
9 Ok(crate::util::truncate(val))
10 }
11
12 #[inline]
13 pub fn inner_u64() -> Result<u64, Error> {
14 Ok(get_random_u64())
15 }
16
17 #[inline]
18 pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
19 use core::ptr::copy_nonoverlapping;
20 use wasi::random::random::get_random_u64;
21
22 let (prefix, chunks, suffix) = unsafe { dest.align_to_mut::<MaybeUninit<u64>>() };
23
24 // We use `get_random_u64` instead of `get_random_bytes` because the latter creates
25 // an allocation due to the Wit IDL [restrictions][0]. This should be fine since
26 // the main use case of `getrandom` is seed generation.
27 //
28 // [0]: https://github.com/WebAssembly/wasi-random/issues/27
29 if !prefix.is_empty() {
30 let val = get_random_u64();
31 let src = (&val as *const u64).cast();
32 unsafe {
33 copy_nonoverlapping(src, prefix.as_mut_ptr(), prefix.len());
34 }
35 }
36
37 for dst in chunks {
38 dst.write(get_random_u64());
39 }
40
41 if !suffix.is_empty() {
42 let val = get_random_u64();
43 let src = (&val as *const u64).cast();
44 unsafe {
45 copy_nonoverlapping(src, suffix.as_mut_ptr(), suffix.len());
46 }
47 }
48
49 Ok(())
50 }