Skip to main content

mirascript_vm/
runtime_providers.rs

1use std::{
2    rc::Rc,
3    time::{SystemTime, UNIX_EPOCH},
4};
5
6struct SystemRuntimeProviders;
7impl RuntimeProviders for SystemRuntimeProviders {}
8
9/// Host capabilities used by non-deterministic standard-library functions.
10pub trait RuntimeProviders {
11    /// Return a uniformly distributed random number in `[0, 1)`.
12    fn random(&self) -> f64 {
13        rand::random()
14    }
15
16    /// Return the current Unix timestamp in milliseconds.
17    fn now_millis(&self) -> i64 {
18        SystemTime::now()
19            .duration_since(UNIX_EPOCH)
20            .unwrap_or_default()
21            .as_millis() as i64
22    }
23
24    /// Emit one debug message from a script.
25    fn debug(&self, message: &str) {
26        eprintln!("{message}");
27    }
28}
29
30std::thread_local! {
31    static DEFAULT_RUNTIME_PROVIDERS: Rc<dyn RuntimeProviders> = Rc::new(SystemRuntimeProviders);
32}
33
34/// Return a reference-counted handle to the default runtime providers.
35pub fn default_runtime_providers() -> Rc<dyn RuntimeProviders> {
36    DEFAULT_RUNTIME_PROVIDERS.with(Clone::clone)
37}