siws/
timestamp.rs

1use core::{
2    cmp::Ordering,
3    fmt::{self, Display, Formatter},
4    str::FromStr,
5};
6use time::{format_description::well_known::Rfc3339, OffsetDateTime};
7
8#[derive(Clone, Debug, PartialEq, Eq)]
9/// Wrapper for [OffsetDateTime], meant to enable transitivity of deserialisation and serialisation.
10pub struct TimeStamp(String, OffsetDateTime);
11
12impl From<OffsetDateTime> for TimeStamp {
13    fn from(t: OffsetDateTime) -> Self {
14        Self(t.format(&Rfc3339).expect("Rfc3339 formatting works"), t)
15    }
16}
17
18impl AsRef<OffsetDateTime> for TimeStamp {
19    fn as_ref(&self) -> &OffsetDateTime {
20        &self.1
21    }
22}
23
24impl Display for TimeStamp {
25    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
26        write!(f, "{}", &self.0)
27    }
28}
29
30impl FromStr for TimeStamp {
31    type Err = time::Error;
32
33    fn from_str(s: &str) -> Result<Self, Self::Err> {
34        Ok(Self(s.into(), OffsetDateTime::parse(s, &Rfc3339)?))
35    }
36}
37
38impl PartialEq<OffsetDateTime> for TimeStamp {
39    fn eq(&self, other: &OffsetDateTime) -> bool {
40        &self.1 == other
41    }
42}
43
44impl PartialOrd<OffsetDateTime> for TimeStamp {
45    fn partial_cmp(&self, other: &OffsetDateTime) -> Option<Ordering> {
46        self.1.partial_cmp(other)
47    }
48}