-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrandom.rs
More file actions
80 lines (75 loc) · 2.83 KB
/
Copy pathrandom.rs
File metadata and controls
80 lines (75 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use crate::{StdFunction, StdlibModule, StdlibRegistry};
use std::collections::HashMap;
use std::rc::Rc;
use techscript_runtime::{error::RuntimeError, value::RuntimeValue};
impl StdlibRegistry {
pub fn register_random(&mut self) {
let mut exports: HashMap<String, Rc<dyn techscript_runtime::function::Callable>> =
HashMap::new();
exports.insert(
"int".to_string(),
Rc::new(StdFunction {
name: "int".to_string(),
arity: 2,
callback: |_ctx, args| {
let min = args[0].try_into_int()?;
let max = args[1].try_into_int()?;
let rand_num = min
+ (std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos() as i64
% (max - min + 1));
Ok(RuntimeValue::Int(rand_num))
},
}),
);
exports.insert(
"float".to_string(),
Rc::new(StdFunction {
name: "float".to_string(),
arity: 2,
callback: |_ctx, args| {
let min = args[0].try_into_float()?;
let max = args[1].try_into_float()?;
let nano = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.subsec_nanos() as f64;
let pct = nano / 1_000_000_000.0;
Ok(RuntimeValue::Float(min + pct * (max - min)))
},
}),
);
exports.insert(
"choice".to_string(),
Rc::new(StdFunction {
name: "choice".to_string(),
arity: 1,
callback: |_ctx, args| {
if let RuntimeValue::List { items, .. } = &args[0] {
let borrow = items.borrow();
if !borrow.is_empty() {
let idx = (std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.subsec_nanos() as usize)
% borrow.len();
return Ok(borrow[idx].clone());
}
}
Ok(RuntimeValue::Null)
},
}),
);
self.register_module(
"std.random",
StdlibModule {
name: "std.random".to_string(),
version: "1.0.0".to_string(),
exports,
required_capabilities: Vec::new(),
},
);
}
}