openssh_sftp_client/
unix_timestamp.rs

1use super::{lowlevel, UnixTimeStampError};
2use std::time::{Duration, SystemTime};
3
4/// Default value is 1970-01-01 00:00:00 UTC.
5///
6/// UnixTimeStamp stores number of seconds elapsed since 1970-01-01 00:00:00 UTC
7/// as `u32`.
8#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
9#[repr(transparent)]
10pub struct UnixTimeStamp(pub(crate) lowlevel::UnixTimeStamp);
11
12impl UnixTimeStamp {
13    /// Create new unix timestamp from `system_time`.
14    pub fn new(system_time: SystemTime) -> Result<Self, UnixTimeStampError> {
15        lowlevel::UnixTimeStamp::new(system_time).map(Self)
16    }
17
18    /// Return unix epoch, same as [`UnixTimeStamp::default`]
19    pub const fn unix_epoch() -> Self {
20        Self(lowlevel::UnixTimeStamp::unix_epoch())
21    }
22
23    /// Return `None` if [`std::time::SystemTime`] cannot hold the timestamp.
24    pub fn from_raw(elapsed: u32) -> Option<Self> {
25        lowlevel::UnixTimeStamp::from_raw(elapsed).map(Self)
26    }
27
28    /// Into `u32` which is used to internally store the timestamp in seconds.
29    pub fn into_raw(self) -> u32 {
30        self.0.into_raw()
31    }
32
33    /// Convert timestamp to [`Duration`].
34    pub fn as_duration(self) -> Duration {
35        self.0.as_duration()
36    }
37
38    /// Convert timestamp back to [`SystemTime`].
39    pub fn as_system_time(self) -> SystemTime {
40        self.0.as_system_time()
41    }
42}