Skip to main content

ferrijs_std/utils/
time.rs

1use std::{
2    sync::atomic::{AtomicU64, Ordering},
3    time::SystemTime,
4};
5
6static TIME_ORIGIN: AtomicU64 = AtomicU64::new(0);
7
8/// Get the current time in nanoseconds.
9///
10/// # Safety
11/// - Good until the year 2554
12/// - Always use a checked substraction since this can return 0
13pub fn now_nanos() -> u64 {
14    SystemTime::now()
15        .duration_since(std::time::UNIX_EPOCH)
16        .unwrap_or_default()
17        .as_nanos() as u64
18}
19
20/// Get the current time in millis.
21///
22/// # Safety
23/// - Good until the year 2554
24/// - Always use a checked substraction since this can return 0
25pub fn now_millis() -> i64 {
26    SystemTime::now()
27        .duration_since(std::time::UNIX_EPOCH)
28        .unwrap_or_default()
29        .as_millis() as i64
30}
31
32/// Get the origin time in nanoseconds.
33///
34/// # Safety
35/// - Good until the year 2554
36/// - Always use a checked substraction since this can return 0
37pub fn origin_nanos() -> u64 {
38    TIME_ORIGIN.load(Ordering::Relaxed)
39}
40
41// For accuracy reasons, this function should be executed when the vm is initialized
42pub fn init() {
43    if TIME_ORIGIN.load(Ordering::Relaxed) == 0 {
44        let time_origin = now_nanos();
45        TIME_ORIGIN.store(time_origin, Ordering::Relaxed)
46    }
47}