spacetimedb_sats/
timestamp.rs1use anyhow::Context;
2use chrono::DateTime;
3
4use crate::{de::Deserialize, impl_st, ser::Serialize, time_duration::TimeDuration, AlgebraicType, AlgebraicValue};
5use std::fmt;
6use std::ops::{Add, AddAssign, Sub, SubAssign};
7use std::time::{Duration, SystemTime};
8
9#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash, Serialize, Deserialize, Debug)]
10#[sats(crate = crate)]
11pub struct Timestamp {
13 __timestamp_micros_since_unix_epoch__: i64,
14}
15
16impl_st!([] Timestamp, AlgebraicType::timestamp());
17
18impl Timestamp {
19 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
20 pub fn now() -> Self {
21 Self::from_system_time(SystemTime::now())
22 }
23
24 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
25 #[deprecated = "Timestamp::now() is stubbed and will panic. Read the `.timestamp` field of a `ReducerContext` instead."]
26 pub fn now() -> Self {
27 unimplemented!()
28 }
29
30 pub const UNIX_EPOCH: Self = Self {
31 __timestamp_micros_since_unix_epoch__: 0,
32 };
33
34 pub fn to_micros_since_unix_epoch(self) -> i64 {
39 self.__timestamp_micros_since_unix_epoch__
40 }
41
42 pub fn from_micros_since_unix_epoch(micros: i64) -> Self {
47 Self {
48 __timestamp_micros_since_unix_epoch__: micros,
49 }
50 }
51
52 pub fn from_time_duration_since_unix_epoch(time_duration: TimeDuration) -> Self {
53 Self::from_micros_since_unix_epoch(time_duration.to_micros())
54 }
55
56 pub fn to_time_duration_since_unix_epoch(self) -> TimeDuration {
57 TimeDuration::from_micros(self.to_micros_since_unix_epoch())
58 }
59
60 pub fn to_duration_since_unix_epoch(self) -> Result<Duration, Duration> {
62 let micros = self.to_micros_since_unix_epoch();
63 if micros >= 0 {
64 Ok(Duration::from_micros(micros as u64))
65 } else {
66 Err(Duration::from_micros((-micros) as u64))
67 }
68 }
69
70 pub fn from_duration_since_unix_epoch(duration: Duration) -> Self {
74 Self::from_micros_since_unix_epoch(
75 duration
76 .as_micros()
77 .try_into()
78 .expect("Duration since Unix epoch overflows i64 microseconds"),
79 )
80 }
81
82 pub fn to_system_time(self) -> SystemTime {
91 match self.to_duration_since_unix_epoch() {
92 Ok(positive) => SystemTime::UNIX_EPOCH
93 .checked_add(positive)
94 .expect("Timestamp with i64 microseconds since Unix epoch overflows SystemTime"),
95 Err(negative) => SystemTime::UNIX_EPOCH
96 .checked_sub(negative)
97 .expect("Timestamp with i64 microseconds before Unix epoch overflows SystemTime"),
98 }
99 }
100
101 pub fn from_system_time(system_time: SystemTime) -> Self {
108 let duration = system_time
109 .duration_since(SystemTime::UNIX_EPOCH)
110 .expect("SystemTime predates the Unix epoch");
111 Self::from_duration_since_unix_epoch(duration)
112 }
113
114 pub fn duration_since(self, earlier: Timestamp) -> Option<Duration> {
119 self.time_duration_since(earlier)?.to_duration().ok()
120 }
121
122 pub fn time_duration_since(self, earlier: Timestamp) -> Option<TimeDuration> {
128 let delta = self
129 .to_micros_since_unix_epoch()
130 .checked_sub(earlier.to_micros_since_unix_epoch())?;
131 Some(TimeDuration::from_micros(delta))
132 }
133
134 pub fn parse_from_rfc3339(str: &str) -> anyhow::Result<Timestamp> {
136 DateTime::parse_from_rfc3339(str)
137 .map_err(|err| anyhow::anyhow!(err))
138 .with_context(|| "Invalid timestamp format. Expected RFC 3339 format (e.g. '2025-02-10 15:45:30').")
139 .map(|dt| dt.timestamp_micros())
140 .map(Timestamp::from_micros_since_unix_epoch)
141 }
142
143 pub fn checked_add(&self, duration: TimeDuration) -> Option<Self> {
146 self.__timestamp_micros_since_unix_epoch__
147 .checked_add(duration.to_micros())
148 .map(Timestamp::from_micros_since_unix_epoch)
149 }
150
151 pub fn checked_sub(&self, duration: TimeDuration) -> Option<Self> {
154 self.__timestamp_micros_since_unix_epoch__
155 .checked_sub(duration.to_micros())
156 .map(Timestamp::from_micros_since_unix_epoch)
157 }
158
159 pub fn checked_add_duration(&self, duration: Duration) -> Option<Self> {
164 self.checked_add(TimeDuration::from_duration(duration))
165 }
166
167 pub fn checked_sub_duration(&self, duration: Duration) -> Option<Self> {
172 self.checked_sub(TimeDuration::from_duration(duration))
173 }
174 pub fn to_rfc3339(&self) -> anyhow::Result<String> {
176 DateTime::from_timestamp_micros(self.to_micros_since_unix_epoch())
177 .map(|t| t.to_rfc3339())
178 .ok_or_else(|| anyhow::anyhow!("Timestamp with i64 microseconds since Unix epoch overflows DateTime"))
179 .with_context(|| self.to_micros_since_unix_epoch())
180 }
181}
182
183impl Add<TimeDuration> for Timestamp {
184 type Output = Self;
185
186 fn add(self, other: TimeDuration) -> Self::Output {
187 self.checked_add(other).unwrap()
188 }
189}
190
191impl Add<Duration> for Timestamp {
192 type Output = Self;
193
194 fn add(self, other: Duration) -> Self::Output {
195 self.checked_add_duration(other).unwrap()
196 }
197}
198
199impl Sub<TimeDuration> for Timestamp {
200 type Output = Self;
201
202 fn sub(self, other: TimeDuration) -> Self::Output {
203 self.checked_sub(other).unwrap()
204 }
205}
206
207impl Sub<Duration> for Timestamp {
208 type Output = Self;
209
210 fn sub(self, other: Duration) -> Self::Output {
211 self.checked_sub_duration(other).unwrap()
212 }
213}
214
215impl AddAssign<TimeDuration> for Timestamp {
216 fn add_assign(&mut self, other: TimeDuration) {
217 *self = *self + other;
218 }
219}
220
221impl AddAssign<Duration> for Timestamp {
222 fn add_assign(&mut self, other: Duration) {
223 *self = *self + other;
224 }
225}
226
227impl SubAssign<TimeDuration> for Timestamp {
228 fn sub_assign(&mut self, rhs: TimeDuration) {
229 *self = *self - rhs;
230 }
231}
232
233impl SubAssign<Duration> for Timestamp {
234 fn sub_assign(&mut self, rhs: Duration) {
235 *self = *self - rhs;
236 }
237}
238
239pub(crate) const MICROSECONDS_PER_SECOND: i64 = 1_000_000;
240
241impl fmt::Display for Timestamp {
242 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243 write!(f, "{}", self.to_rfc3339().unwrap())
244 }
245}
246
247impl From<SystemTime> for Timestamp {
248 fn from(system_time: SystemTime) -> Self {
249 Self::from_system_time(system_time)
250 }
251}
252
253impl From<Timestamp> for SystemTime {
254 fn from(timestamp: Timestamp) -> Self {
255 timestamp.to_system_time()
256 }
257}
258
259impl From<Timestamp> for AlgebraicValue {
260 fn from(value: Timestamp) -> Self {
261 AlgebraicValue::product([value.to_micros_since_unix_epoch().into()])
262 }
263}
264
265#[cfg(test)]
266mod test {
267 use super::*;
268 use crate::GroundSpacetimeType;
269 use proptest::prelude::*;
270
271 fn round_to_micros(st: SystemTime) -> SystemTime {
272 let duration = st.duration_since(SystemTime::UNIX_EPOCH).unwrap();
273 let micros = duration.as_micros();
274 SystemTime::UNIX_EPOCH + Duration::from_micros(micros as _)
275 }
276
277 #[test]
278 fn timestamp_type_matches() {
279 assert_eq!(AlgebraicType::timestamp(), Timestamp::get_type());
280 assert!(Timestamp::get_type().is_timestamp());
281 assert!(Timestamp::get_type().is_special());
282 }
283
284 #[test]
285 fn round_trip_systemtime_through_timestamp() {
286 let now = round_to_micros(SystemTime::now());
287 let timestamp = Timestamp::from(now);
288 let now_prime = SystemTime::from(timestamp);
289 assert_eq!(now, now_prime);
290 }
291
292 proptest! {
293 #[test]
294 fn round_trip_timestamp_through_systemtime(micros in any::<i64>().prop_map(|n| n.abs())) {
295 let timestamp = Timestamp::from_micros_since_unix_epoch(micros);
296 let system_time = SystemTime::from(timestamp);
297 let timestamp_prime = Timestamp::from(system_time);
298 prop_assert_eq!(timestamp_prime, timestamp);
299 prop_assert_eq!(timestamp_prime.to_micros_since_unix_epoch(), micros);
300 }
301
302 #[test]
303 fn arithmetic_with_timeduration(lhs in any::<i64>(), rhs in any::<i64>()) {
304 let lhs_timestamp = Timestamp::from_micros_since_unix_epoch(lhs);
305 let rhs_time_duration = TimeDuration::from_micros(rhs);
306
307 if let Some(sum) = lhs.checked_add(rhs) {
308 let sum_timestamp = lhs_timestamp.checked_add(rhs_time_duration);
309 prop_assert!(sum_timestamp.is_some());
310 prop_assert_eq!(sum_timestamp.unwrap().to_micros_since_unix_epoch(), sum);
311
312 prop_assert_eq!((lhs_timestamp + rhs_time_duration).to_micros_since_unix_epoch(), sum);
313
314 let mut sum_assign = lhs_timestamp;
315 sum_assign += rhs_time_duration;
316 prop_assert_eq!(sum_assign.to_micros_since_unix_epoch(), sum);
317 } else {
318 prop_assert!(lhs_timestamp.checked_add(rhs_time_duration).is_none());
319 }
320
321 if let Some(diff) = lhs.checked_sub(rhs) {
322 let diff_timestamp = lhs_timestamp.checked_sub(rhs_time_duration);
323 prop_assert!(diff_timestamp.is_some());
324 prop_assert_eq!(diff_timestamp.unwrap().to_micros_since_unix_epoch(), diff);
325
326 prop_assert_eq!((lhs_timestamp - rhs_time_duration).to_micros_since_unix_epoch(), diff);
327
328 let mut diff_assign = lhs_timestamp;
329 diff_assign -= rhs_time_duration;
330 prop_assert_eq!(diff_assign.to_micros_since_unix_epoch(), diff);
331 } else {
332 prop_assert!(lhs_timestamp.checked_sub(rhs_time_duration).is_none());
333 }
334 }
335
336 }
339}