Skip to content
This repository has been archived by the owner on Oct 13, 2023. It is now read-only.

Commit

Permalink
Add a way to get a random u64.
Browse files Browse the repository at this point in the history
This anticipates WebAssembly/wasi-random#18.
  • Loading branch information
sunfishcode committed Dec 21, 2022
1 parent bd62536 commit 345ee9c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
6 changes: 5 additions & 1 deletion host/src/random.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@ use crate::{wasi_random, WasiCtx};

#[async_trait::async_trait]
impl wasi_random::WasiRandom for WasiCtx {
async fn getrandom(&mut self, len: u32) -> anyhow::Result<Vec<u8>> {
async fn get_random_bytes(&mut self, len: u32) -> anyhow::Result<Vec<u8>> {
Ok((&mut self.random)
.sample_iter(Standard)
.take(len as usize)
.collect())
}

async fn get_random_u64(&mut self) -> anyhow::Result<u64> {
Ok((&mut self.random).sample(Standard))
}
}
11 changes: 10 additions & 1 deletion wit/wasi.wit
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,16 @@ interface wasi-random {
///
/// Deterministic environments must omit this function, rather than
/// implementing it with deterministic data.
getrandom: func(len: u32) -> list<u8>
get-random-bytes: func(len: u32) -> list<u8>

/// Return a random `u64` value.
///
/// This function must produce data from an adaquately seeded CSPRNG, so it
/// must not block, and the returned data is always unpredictable.
///
/// Deterministic environments must omit this function, rather than
/// implementing it with deterministic data.
get-random-u64: func() -> u64

/// A value containing 128 random bits.
///
Expand Down

0 comments on commit 345ee9c

Please sign in to comment.