add, fix tests

This commit is contained in:
Pat Hickey
2021-01-04 12:33:13 -08:00
parent 48554a1a5c
commit 50554d376b
2 changed files with 31 additions and 2 deletions

View File

@@ -5,6 +5,8 @@ pub trait WasiRandom {
fn get(&self, buf: &mut [u8]) -> Result<(), Error>; fn get(&self, buf: &mut [u8]) -> Result<(), Error>;
} }
/// Implement `WasiRandom` using the `getrandom` crate, which selects your system's best entropy
/// source.
pub struct GetRandom; pub struct GetRandom;
impl WasiRandom for GetRandom { impl WasiRandom for GetRandom {
@@ -14,6 +16,7 @@ impl WasiRandom for GetRandom {
} }
} }
/// Implement `WasiRandom` using a deterministic cycle of bytes.
pub struct Deterministic { pub struct Deterministic {
sequence: RefCell<std::iter::Cycle<std::vec::IntoIter<u8>>>, sequence: RefCell<std::iter::Cycle<std::vec::IntoIter<u8>>>,
} }
@@ -35,3 +38,17 @@ impl WasiRandom for Deterministic {
Ok(()) Ok(())
} }
} }
#[cfg(test)]
mod test {
use super::*;
#[test]
fn deterministic() {
let det = Deterministic::new(vec![1, 2, 3, 4]);
let mut buf = vec![0; 1024];
det.get(&mut buf).expect("get randomness");
for (ix, b) in buf.iter().enumerate() {
assert_eq!(*b, (ix % 4) as u8 + 1)
}
}
}

View File

@@ -20,11 +20,11 @@ use system_interface::fs::{Advice, FileIoExt};
/// A variety of `From` impls are provided so that common pipe types are easy to create. For example: /// A variety of `From` impls are provided so that common pipe types are easy to create. For example:
/// ///
/// ``` /// ```
/// # use wasi_c2::WasiCtxBuilder; /// # use wasi_c2::WasiCtx;
/// # use wasi_c2::virt::pipe::ReadPipe; /// # use wasi_c2::virt::pipe::ReadPipe;
/// let mut ctx = WasiCtx::builder(); /// let mut ctx = WasiCtx::builder();
/// let stdin = ReadPipe::from("hello from stdin!"); /// let stdin = ReadPipe::from("hello from stdin!");
/// ctx.stdin(stdin); /// ctx.stdin(Box::new(stdin));
/// ``` /// ```
#[derive(Debug)] #[derive(Debug)]
pub struct ReadPipe<R: Read> { pub struct ReadPipe<R: Read> {
@@ -207,6 +207,18 @@ impl<R: Read> WasiFile for ReadPipe<R> {
} }
/// A virtual pipe write end. /// A virtual pipe write end.
///
/// ```
/// # use wasi_c2::WasiCtx;
/// # use wasi_c2::virt::pipe::WritePipe;
/// let mut ctx = WasiCtx::builder();
/// let stdout = WritePipe::new_in_memory();
/// ctx.stdout(Box::new(stdout.clone()));
/// // use ctx in an instance, then make sure it is dropped:
/// drop(ctx);
/// let contents: Vec<u8> = stdout.try_into_inner().expect("sole remaining reference to WritePipe").into_inner();
/// println!("contents of stdout: {:?}", contents);
/// ```
#[derive(Debug)] #[derive(Debug)]
pub struct WritePipe<W: Write> { pub struct WritePipe<W: Write> {
writer: Arc<RwLock<W>>, writer: Arc<RwLock<W>>,