tvl-depot/tvix/eval/src/builtins/impure.rs
Vincent Ambo 89dc26cece feat(tvix/eval): implement builtins.currentTime
Returns time since epoch in seconds.

This has a slight behaviour difference from Nix, in that we don't pin
the time between REPL entries (Nix pins it for the program lifetime),
but this is probably inconsequential as long as it is pinned during an
evaluation.

Change-Id: I010c02e93097a209d8ad69e278397c7e30e54c86
Reviewed-on: https://cl.tvl.fyi/c/depot/+/6846
Tested-by: BuildkiteCI
Reviewed-by: grfn <grfn@gws.fyi>
Reviewed-by: wpcarro <wpcarro@gmail.com>
2022-10-04 08:03:50 +00:00

36 lines
986 B
Rust

use std::{
collections::BTreeMap,
time::{SystemTime, UNIX_EPOCH},
};
use crate::{
value::{Builtin, NixString},
Value,
};
fn impure_builtins() -> Vec<Builtin> {
vec![]
}
/// Return all impure builtins, that is all builtins which may perform I/O outside of the VM and so
/// cannot be used in all contexts (e.g. WASM).
pub(super) fn builtins() -> BTreeMap<NixString, Value> {
let mut map: BTreeMap<NixString, Value> = impure_builtins()
.into_iter()
.map(|b| (b.name().into(), Value::Builtin(b)))
.collect();
// currentTime pins the time at which evaluation was started
{
let seconds = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(dur) => dur.as_secs() as i64,
// This case is hit if the system time is *before* epoch.
Err(err) => -(err.duration().as_secs() as i64),
};
map.insert(NixString::from("currentTime"), Value::Integer(seconds));
}
map
}