Debian Codegraph @

.cargo/vendor/getrandom/src/backends/wasi_p2.rs

raw
1 //! Implementation for WASI Preview 2.
2 use crate::Error;
3 use core::{mem::MaybeUninit, ptr::copy_nonoverlapping};
4 use wasip2::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 let (prefix, chunks, suffix) = unsafe { dest.align_to_mut::<MaybeUninit<u64>>() };
20
21 // We use `get_random_u64` instead of `get_random_bytes` because the latter creates
22 // an allocation due to the Wit IDL [restrictions][0]. This should be fine since
23 // the main use case of `getrandom` is seed generation.
24 //
25 // [0]: https://github.com/WebAssembly/wasi-random/issues/27
26 if !prefix.is_empty() {
27 let val = get_random_u64();
28 let src = (&val as *const u64).cast();
29 unsafe {
30 copy_nonoverlapping(src, prefix.as_mut_ptr(), prefix.len());
31 }
32 }
33
34 for dst in chunks {
35 dst.write(get_random_u64());
36 }
37
38 if !suffix.is_empty() {
39 let val = get_random_u64();
40 let src = (&val as *const u64).cast();
41 unsafe {
42 copy_nonoverlapping(src, suffix.as_mut_ptr(), suffix.len());
43 }
44 }
45
46 Ok(())
47 }