crafting-interpreters/src/native_functions.rs

44 lines
933 B
Rust

use std::{
rc::Rc,
time::{SystemTime, UNIX_EPOCH},
};
use ordered_float::OrderedFloat;
use crate::{
callable::{Callable, CallingError},
interpreter::Interpreter,
value::{CallableType, 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(OrderedFloat(since_the_epoch.as_secs_f64())))
}
}
pub fn all() -> Vec<(String, Value)> {
vec![(
"clock".into(),
Value::Callable((Rc::new(Clock {}), CallableType::Function)),
)]
}