Browse Source

add, fix tests

pull/2577/head
Pat Hickey 4 years ago
parent
commit
50554d376b
  1. 17
      crates/wasi-c2/src/random.rs
  2. 16
      crates/wasi-c2/src/virt/pipe.rs

17
crates/wasi-c2/src/random.rs

@ -5,6 +5,8 @@ pub trait WasiRandom {
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;
impl WasiRandom for GetRandom {
@ -14,6 +16,7 @@ impl WasiRandom for GetRandom {
}
}
/// Implement `WasiRandom` using a deterministic cycle of bytes.
pub struct Deterministic {
sequence: RefCell<std::iter::Cycle<std::vec::IntoIter<u8>>>,
}
@ -35,3 +38,17 @@ impl WasiRandom for Deterministic {
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)
}
}
}

16
crates/wasi-c2/src/virt/pipe.rs

@ -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:
///
/// ```
/// # use wasi_c2::WasiCtxBuilder;
/// # use wasi_c2::WasiCtx;
/// # use wasi_c2::virt::pipe::ReadPipe;
/// let mut ctx = WasiCtx::builder();
/// let stdin = ReadPipe::from("hello from stdin!");
/// ctx.stdin(stdin);
/// ctx.stdin(Box::new(stdin));
/// ```
#[derive(Debug)]
pub struct ReadPipe<R: Read> {
@ -207,6 +207,18 @@ impl<R: Read> WasiFile for ReadPipe<R> {
}
/// 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)]
pub struct WritePipe<W: Write> {
writer: Arc<RwLock<W>>,

Loading…
Cancel
Save