veecle_osal_api/time/system_time.rs
1//! Provides system time functionality with support for time synchronization.
2
3use crate::time::Duration;
4
5/// Provides a measurement of the system time.
6pub trait SystemTime {
7 /// Calculates the [`Duration`] elapsed since epoch.
8 ///
9 /// ## Notes
10 ///
11 /// OSAL implementations might require time to be synchronized by using the [`SystemTimeSync`] before using this
12 /// function. Review the documentation on the implementation you are using to learn platform-specific information.
13 ///
14 /// ## Errors
15 ///
16 /// - [`SystemTimeError::Unsynchronized`] when system was not synchronized previously.
17 fn duration_since_epoch() -> Result<Duration, SystemTimeError>;
18}
19
20/// Allows manual synchronization of [`SystemTime`].
21pub trait SystemTimeSync {
22 /// Updates the current system time.
23 ///
24 /// Use this to synchronize with real-world clock (e.g., provide time obtained from NTP).
25 ///
26 /// ## Errors
27 ///
28 /// - [`SystemTimeError::EpochIsLaterThanStartTime`] when the provided duration is less than the program's execution
29 /// time.
30 fn set_system_time(elapsed_from_epoch: Duration) -> Result<(), SystemTimeError>;
31}
32
33/// An error that may happen while working with System Time.
34#[derive(Debug, Eq, PartialEq)]
35pub enum SystemTimeError {
36 /// Occurs when an attempt is made to get system time, but it was not synchronized earlier.
37 Unsynchronized,
38 /// Occurs when an attempt is made to synchronize using an epoch time that is later than the program's start time.
39 EpochIsLaterThanStartTime,
40}
41
42impl core::error::Error for SystemTimeError {
43 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
44 match self {
45 SystemTimeError::Unsynchronized => None,
46 SystemTimeError::EpochIsLaterThanStartTime => None,
47 }
48 }
49}
50
51impl core::fmt::Display for SystemTimeError {
52 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
53 match self {
54 SystemTimeError::Unsynchronized => write!(f, "{self:?}"),
55 SystemTimeError::EpochIsLaterThanStartTime => write!(f, "{self:?}"),
56 }
57 }
58}