ora_common/
lib.rs

1//! Common types and functions for Ora.
2
3#![warn(clippy::pedantic, missing_docs)]
4#![allow(clippy::module_name_repetitions, clippy::default_trait_access)]
5
6use std::time::{Duration, SystemTime, UNIX_EPOCH};
7
8use serde::{Deserialize, Serialize};
9use time::OffsetDateTime;
10
11pub mod schedule;
12pub mod task;
13pub mod timeout;
14
15/// UTC timestamp used by Ora, nanoseconds since the unix epoch.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
17#[repr(transparent)]
18#[serde(transparent)]
19#[must_use]
20pub struct UnixNanos(pub u64);
21
22impl UnixNanos {
23    /// Get the current timestamp from [`SystemTime`].
24    pub fn now() -> Self {
25        UnixNanos(
26            SystemTime::now()
27                .duration_since(UNIX_EPOCH)
28                .unwrap_or(Duration::ZERO)
29                .as_nanos()
30                .try_into()
31                .unwrap_or(0),
32        )
33    }
34}
35
36impl From<u64> for UnixNanos {
37    fn from(value: u64) -> Self {
38        Self(value)
39    }
40}
41
42impl From<UnixNanos> for u64 {
43    fn from(value: UnixNanos) -> Self {
44        value.0
45    }
46}
47
48impl From<UnixNanos> for OffsetDateTime {
49    #[allow(clippy::cast_lossless)]
50    fn from(value: UnixNanos) -> Self {
51        OffsetDateTime::from_unix_timestamp_nanos(value.0 as _).unwrap()
52    }
53}
54
55impl From<OffsetDateTime> for UnixNanos {
56    fn from(value: OffsetDateTime) -> Self {
57        UnixNanos(value.unix_timestamp_nanos().try_into().unwrap_or(0))
58    }
59}