Skip to main content

weirdnet_update/
time.rs

1//! Seconds since the Unix epoch, UTC.
2
3use serde::{Deserialize, Serialize};
4use std::time::{SystemTime, UNIX_EPOCH};
5
6/// A point in time as whole seconds since the Unix epoch (UTC).
7#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
8#[serde(transparent)]
9pub struct Timestamp(pub u64);
10
11impl Timestamp {
12    /// The current system time. A clock before 1970 reads as 0.
13    pub fn now() -> Self {
14        Self(SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0))
15    }
16
17    /// This time plus `secs`, saturating.
18    pub fn plus(self, secs: u64) -> Self {
19        Self(self.0.saturating_add(secs))
20    }
21
22    /// This time minus `secs`, saturating at 0.
23    pub fn minus(self, secs: u64) -> Self {
24        Self(self.0.saturating_sub(secs))
25    }
26}