crafting-interpreters/rust/rox/src/native_functions.rs

40 lines
820 B
Rust
Raw Normal View History

2025-02-13 12:29:31 +01:00
use std::{
rc::Rc,
time::{SystemTime, UNIX_EPOCH},
};
use crate::{
callable::{Callable, CallingError},
interpreter::Interpreter,
value::Value,
};
struct Clock;
impl Callable for Clock {
fn name(&self) -> String {
"clock".into()
}
fn arity(&self) -> usize {
0
}
fn call(
&self,
_interpreter: &mut Interpreter,
_args: Vec<crate::value::Value>,
) -> Result<Value, CallingError> {
let start = SystemTime::now();
let since_the_epoch = start
.duration_since(UNIX_EPOCH)
.map_err(|e| CallingError::CallFailed(e.to_string()))?;
Ok(Value::Number(since_the_epoch.as_secs_f64()))
}
}
pub fn all() -> Vec<(String, Value)> {
vec![("clock".into(), Value::Callable(Rc::new(Clock {})))]
}