Skip to content

Commit

Permalink
wasi: add random_get
Browse files Browse the repository at this point in the history
  • Loading branch information
skanehira committed Nov 22, 2023
1 parent 2e2ef40 commit aa4c41e
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 2 deletions.
58 changes: 56 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ num-derive = "0.3"
thiserror = "1.0.39"
log = "0.4.17"
pretty_env_logger = "0.4.0"
rand = "0.8.5"

[dev-dependencies]
wat = "1.0.62"
Expand Down
10 changes: 10 additions & 0 deletions examples/rjo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use anyhow::Result;
use chibiwasm::wasi::WasiSnapshotPreview1;
use chibiwasm::Runtime;

fn main() -> Result<()> {
let wasi = WasiSnapshotPreview1::default();
let mut runtime = Runtime::from_file("examples/rjo.wasm", Some(Box::new(wasi)))?;
runtime.call("_start".into(), vec![])?;
Ok(())
}
Binary file added examples/rjo.wasm
Binary file not shown.
24 changes: 24 additions & 0 deletions src/wasi/wasi_snapshot_preview1/preview1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{
Store, Value,
};
use anyhow::{Context as _, Result};
use rand::prelude::*;
use std::{
cell::RefCell,
rc::Rc,
Expand Down Expand Up @@ -32,6 +33,7 @@ impl Importer for WasiSnapshotPreview1 {
"environ_sizes_get" => self.environ_sizes_get(store, args),
"args_get" => self.args_get(store, args),
"args_sizes_get" => self.args_sizes_get(store, args),
"random_get" => self.random_get(store, args),
_ => todo!(),
}?;
Ok(Some(value))
Expand Down Expand Up @@ -228,6 +230,28 @@ impl WasiSnapshotPreview1 {

Ok(0.into())
}

fn random_get(&self, store: Rc<RefCell<Store>>, args: Vec<Value>) -> Result<Value> {
let args: Vec<i32> = args.into_iter().map(Into::into).collect();
let (mut offset, buf_len) = (args[0] as usize, args[1] as usize);

let store = store.borrow();
let memory = store.memory.get(0).with_context(|| "not found memory")?;
let mut memory = memory.borrow_mut();

let mut rng = thread_rng();

let distr = rand::distributions::Uniform::new_inclusive(1u32, 100);
for _ in 0..buf_len {
let x = rng.sample(distr);
let mut buf = std::io::Cursor::new(Vec::new());
leb128::write::unsigned(&mut buf, x as u64)?;
memory.write_bytes(offset, buf.into_inner().as_slice())?;
offset += 1;
}

Ok(0.into())
}
}

#[cfg(test)]
Expand Down

0 comments on commit aa4c41e

Please sign in to comment.