Skip to content

Commit

Permalink
Merge pull request hush-shell#37 from caioraposo/std.rand
Browse files Browse the repository at this point in the history
Add std.rand/randint
  • Loading branch information
gahag authored Mar 25, 2023
2 parents 7fa2dc4 + 2bc36cb commit 6f06804
Show file tree
Hide file tree
Showing 3 changed files with 104 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 @@ -28,6 +28,7 @@ serde = "1.0"
serde_json = "1.0"
base64 = "0.13"
hex = "0.4"
rand = "0.8.5"

[dev-dependencies]
assert_matches = "1.5"
Expand Down
47 changes: 47 additions & 0 deletions src/runtime/lib/rand.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use gc::{Finalize, Trace};

use super::{
Float,
NativeFun,
Panic,
RustFun,
Value,
CallContext,
};
use rand::{Rng, thread_rng};

inventory::submit! { RustFun::from(Rand) }
inventory::submit! { RustFun::from(RandInt) }

#[derive(Trace, Finalize)]
struct Rand;

#[derive(Trace, Finalize)]
struct RandInt;

impl NativeFun for Rand {
fn name(&self) -> &'static str { "std.rand" }

fn call(&self, context: CallContext) -> Result<Value, Panic> {
let mut rng = thread_rng();
let args = context.args();
if args.is_empty() {
Ok(Value::Float(Float(rng.gen::<f64>())))
} else {
Err(Panic::invalid_args(args.len() as u32, 0, context.pos))
}
}
}

impl NativeFun for RandInt {
fn name(&self) -> &'static str { "std.randint" }

fn call(&self, context: CallContext) -> Result<Value, Panic> {
let mut rng = thread_rng();
match context.args() {
[ Value::Int(m), Value::Int(n) ] => Ok(Value::Int(rng.gen_range(*m..=*n))),
[ other, _ ] => Err(Panic::type_error(other.copy(), "int", context.pos)),
args => Err(Panic::invalid_args(args.len() as u32, 2, context.pos))
}
}
}

0 comments on commit 6f06804

Please sign in to comment.