otp_std/
time.rs

1//! Current time functionality.
2//!
3//! This module provides the [`now`] function to fetch the current time as seconds since the epoch.
4//! Note that [`now`] can return [`struct@Error`] in case the current time is before the epoch.
5
6use std::time::{SystemTime, SystemTimeError, UNIX_EPOCH};
7
8use miette::Diagnostic;
9use thiserror::Error;
10
11/// The error message for when the system time is before the epoch.
12pub const CURRENT_TIME_BEFORE_EPOCH: &str = "current time is before the epoch";
13
14/// Wraps [`SystemTimeError`] to provide diagnostics.
15#[derive(Debug, Error, Diagnostic)]
16#[error("system time is before epoch")]
17#[diagnostic(code(otp_std::time), help("see the report for more information"))]
18pub struct Error(#[from] pub SystemTimeError);
19
20/// Returns the current time as seconds since the epoch.
21///
22/// # Errors
23///
24/// Returns [`struct@Error`] if the system time is before the epoch.
25pub fn now() -> Result<u64, Error> {
26    SystemTime::now()
27        .duration_since(UNIX_EPOCH)
28        .map(|duration| duration.as_secs())
29        .map_err(Error)
30}
31
32/// Similar to [`now`], but panics if the current time is before the epoch.
33///
34/// # Panics
35///
36/// Panics if the current time is before the epoch.
37pub fn expect_now() -> u64 {
38    now().expect(CURRENT_TIME_BEFORE_EPOCH)
39}