Skip to main content

leodos_libcfs/os/
time.rs

1//! Safe, idiomatic wrappers for OSAL local time APIs.
2//!
3//! This module provides an `OsTime` struct and functions for interacting with
4//! the host operating system's local time, as opposed to the cFE-managed
5//! spacecraft time.
6
7use crate::error::Result;
8use crate::ffi;
9use crate::status::check;
10use core::mem::MaybeUninit;
11
12/// A wrapper around `OS_time_t` representing a specific local time.
13///
14/// This time is based on the underlying OS epoch (e.g., UNIX epoch) and is
15/// distinct from cFE's mission time (`libcfs::time::SysTime`).
16#[derive(Debug, Clone, Copy)]
17#[repr(transparent)]
18pub struct OsTime(pub(crate) ffi::OS_time_t);
19
20impl OsTime {
21    /// Creates an `OsTime` instance from a relative duration in milliseconds.
22    ///
23    /// This is a safe wrapper for `OS_TimeFromRelativeMilliseconds`.
24    #[cfg(not(nos3_cfe))]
25    pub fn from_relative_millis(millis: i32) -> Self {
26        Self(unsafe { ffi::OS_TimeFromRelativeMilliseconds(millis) })
27    }
28
29    /// Calculates the relative duration in milliseconds until this absolute time.
30    ///
31    /// This is a safe wrapper for `OS_TimeToRelativeMilliseconds`.
32    /// Returns `OS_CHECK` (0) if the time is in the past, or `OS_PEND` (-1) if
33    /// the time is too far in the future to be represented.
34    #[cfg(not(nos3_cfe))]
35    pub fn to_relative_millis(&self) -> i32 {
36        unsafe { ffi::OS_TimeToRelativeMilliseconds(self.0) }
37    }
38
39    /// Gets the current local time from the underlying OS.
40    ///
41    /// This is a safe wrapper for `OS_GetLocalTime`.
42    pub fn now() -> Result<Self> {
43        let mut time_struct = MaybeUninit::uninit();
44        check(unsafe { ffi::OS_GetLocalTime(time_struct.as_mut_ptr()) })?;
45        Ok(Self(unsafe { time_struct.assume_init() }))
46    }
47}
48
49/// Sets the local time on the underlying OS.
50///
51/// This is a safe wrapper for `OS_SetLocalTime`.
52pub fn set_local_time(time: OsTime) -> Result<()> {
53    check(unsafe { ffi::OS_SetLocalTime(&time.0) })?;
54    Ok(())
55}