plabble_codec/codec/common/
plabble_date.rs

1use crate::abstractions::EPOCH;
2use time::OffsetDateTime;
3
4/// Convert a date to a Plabble timestamp
5///
6/// # Arguments
7///
8/// * `date` - the date to convert
9///
10/// # Returns
11///
12/// The Plabble timestamp
13///
14/// # Panics
15///
16/// Panics if the timestamp is too large to fit in a u32
17pub fn to_timestamp(date: &OffsetDateTime) -> u32 {
18    (date.unix_timestamp() - EPOCH)
19        .try_into()
20        .expect("Failed to fit timestamp into u32")
21}
22
23/// Convert a Plabble timestamp to a date
24///
25/// # Arguments
26///
27/// * `timestamp` - the timestamp to convert
28///
29/// # Returns
30///
31/// The date
32///
33/// # Panics
34///
35/// Panics if the timestamp is not valid
36pub fn from_timestamp(timestamp: u32) -> OffsetDateTime {
37    OffsetDateTime::from_unix_timestamp(timestamp as i64 + EPOCH).expect("Timestamp is not valid")
38}
39
40#[cfg(test)]
41mod test {
42    use time_macros::datetime;
43
44    #[test]
45    fn can_convert_date_to_timestamp() {
46        let d1 = datetime!(2020-01-01 00:00:00 UTC);
47        let d2 = datetime!(2020-01-01 00:01:00 UTC);
48        let d3 = datetime!(2020-01-01 01:00:00 UTC);
49        let d4 = datetime!(2023-03-21 18:41:30 UTC);
50
51        assert_eq!(super::to_timestamp(&d1), 0);
52        assert_eq!(super::to_timestamp(&d2), 60);
53        assert_eq!(super::to_timestamp(&d3), 3600);
54        assert_eq!(super::to_timestamp(&d4), 101587290);
55    }
56
57    #[test]
58    fn can_convert_timestamp_to_date() {
59        let d1 = datetime!(2020-01-01 00:00:00 UTC);
60        let d2 = datetime!(2020-01-01 00:01:00 UTC);
61        let d3 = datetime!(2020-01-01 01:00:00 UTC);
62        let d4 = datetime!(2023-03-21 18:41:30 UTC);
63
64        assert_eq!(super::from_timestamp(0), d1);
65        assert_eq!(super::from_timestamp(60), d2);
66        assert_eq!(super::from_timestamp(3600), d3);
67        assert_eq!(super::from_timestamp(101587290), d4);
68    }
69}