use std::sync::{Arc, Mutex};
use bock_interp::{BuiltinRegistry, RuntimeError, Value};
pub fn register(registry: &mut BuiltinRegistry) {
registry.register_global("sleep", builtin_sleep);
}
fn builtin_sleep(args: &[Value]) -> Result<Value, RuntimeError> {
let nanos = match args.first() {
Some(Value::Duration(n)) => *n,
Some(Value::Int(n)) => *n, Some(other) => {
return Err(RuntimeError::TypeError(format!(
"sleep expects Duration, got {other}"
)));
}
None => {
return Err(RuntimeError::ArityMismatch {
expected: 1,
got: 0,
});
}
};
let handle = tokio::spawn(async move {
if nanos > 0 {
let dur = std::time::Duration::from_nanos(nanos as u64);
tokio::time::sleep(dur).await;
}
Ok(Value::Void)
});
Ok(Value::Future(Arc::new(Mutex::new(Some(handle)))))
}