kine_core/tz/
system.rs

1use core::{fmt::Display, str::FromStr};
2
3use crate::{Calendar, CalendarTime, OffsetTime, Sigil, TimeZone};
4
5use super::InvalidSigilError;
6
7/// A calendar that counts time like the current system clock
8///
9/// On most platforms this will be either POSIX accounting or UTC-SLS accounting, depending
10/// on how NTP is set.
11///
12/// Note that POSIX time accounting leads to the clock being stalled for one second, which
13/// means that during that second it will become impossible to know how much time has elapsed.
14/// Unfortunately, this means that on such systems it is basically impossible to have precise
15/// time accounting during leap seconds. As such, even `Time::now()` may return wrong results
16/// at these times, in a way similar to if the system clock were not set correctly.
17///
18/// The best idea to improve on this would be to juggle between different clocks so that we
19/// could use a fallback clock (like `CLOCK_MONOTONIC`) during a leap seconds. Contributions
20/// are welcome.
21#[derive(Clone, Copy, PartialEq, Eq)]
22pub struct System;
23
24/// Sigil for the system timezone
25///
26/// This is only exposed so that it is possible to write the `OffsetTime<UtcSigil>` struct.
27#[derive(Clone, Copy, PartialEq, Eq)]
28pub struct SystemSigil;
29
30/// A time clock that ticks like the current system clock
31///
32/// On most platforms this will be either POSIX accounting or UTC-SLS accounting, depending
33/// on how NTP is set.
34///
35/// Note that as this does not know of a calendar, its string functions will be giving out
36/// raw numbers that may not be user-friendly.
37pub type SystemTime = OffsetTime<SystemSigil>;
38
39impl System {
40    /// Retrieve the current date according to the system clock
41    ///
42    /// Note that this is infallible, as the system calendar is by definition always able to
43    /// store a time returned by the system clock.
44    ///
45    /// However, it will panic if running on no-std and not having a known alternative
46    /// implementation for time retrieval.
47    pub fn now() -> SystemTime {
48        Self::now_impl()
49    }
50
51    // TODO: split this into a separate feature so that later on when extern existential types come
52    // in we can allow extern implementations of this?
53    #[cfg(feature = "std")]
54    fn now_impl() -> SystemTime {
55        let duration = std::time::SystemTime::now()
56            .duration_since(std::time::UNIX_EPOCH)
57            .expect("Current time was before posix epoch");
58        let pseudo_nanos = i128::try_from(duration.as_nanos())
59            .expect("Overflow trying to retrieve the current time");
60        // No extra nanoseconds for the `std`-based implementation because it'd be impossible to know
61        let extra_nanos = 0;
62        // TODO: Introduce an implementation of `Time::now()` based on other clocks for platforms that
63        // can so this is not the best precision we could have.
64        SystemTime::from_pseudo_nanos_since_posix_epoch(SystemSigil, pseudo_nanos, extra_nanos)
65    }
66
67    #[cfg(not(feature = "std"))]
68    fn now_impl() -> SystemTime {
69        panic!("Running on no-std with no known implementation of time-getting");
70    }
71}
72
73impl TimeZone for System {
74    type Sigil = SystemSigil;
75}
76
77impl Calendar for System {
78    type Time = SystemTime;
79
80    fn try_now(&self) -> crate::Result<Self::Time> {
81        Ok(Self::now())
82    }
83
84    fn now(&self) -> Self::Time {
85        Self::now()
86    }
87
88    fn write(&self, t: &crate::Time) -> crate::Result<Self::Time> {
89        let t = crate::providers::SYSTEM.write(t)?;
90        Ok(Self::Time::from_pseudo_nanos_since_posix_epoch(
91            SystemSigil,
92            t.as_pseudo_nanos_since_posix_epoch(),
93            t.extra_nanos(),
94        ))
95    }
96}
97
98impl Sigil for SystemSigil {
99    fn read(&self, t: &OffsetTime<Self>) -> crate::Result<crate::TimeResult> {
100        OffsetTime::<crate::providers::SystemSigil>::from_pseudo_nanos_since_posix_epoch(
101            crate::providers::SYSTEM_SIGIL,
102            t.as_pseudo_nanos_since_posix_epoch(),
103            t.extra_nanos(),
104        )
105        .read()
106    }
107}
108
109impl Display for SystemSigil {
110    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
111        f.write_str("Z")
112    }
113}
114
115impl FromStr for SystemSigil {
116    type Err = InvalidSigilError;
117
118    fn from_str(s: &str) -> Result<Self, Self::Err> {
119        match s {
120            "Z" => Ok(SystemSigil),
121            " UTC" => Ok(SystemSigil),
122            _ => Err(InvalidSigilError),
123        }
124    }
125}