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