Skip to main content

harmos_domain/model/storage/
time.rs

1/* ***
2 *
3 * Harmos
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * ***
8 */
9
10/* === Modules === */
11
12pub mod optional {
13    use super::*;
14
15    pub fn serialize<S: Serializer>(value: &Option<Timestamp>, serializer: S) -> Result<S::Ok, S::Error> {
16        value.map(Wire::from).serialize(serializer)
17    }
18
19    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Timestamp>, D::Error> {
20        Option::<Wire>::deserialize(deserializer)?.map(Wire::timestamp).transpose().map_err(serde::de::Error::custom)
21    }
22}
23
24/* === Re-Exports === */
25
26/* === Imports === */
27
28// Standard Library Imports
29use std::time::{Duration, SystemTime as Timestamp, UNIX_EPOCH};
30// Third Party Imports
31use serde::{Deserialize, Deserializer, Serialize, Serializer};
32// Local Imports
33
34/* === Constants === */
35
36/* === Macros === */
37
38/* === Type Aliases === */
39
40/* === Structs === */
41
42#[derive(Serialize, Deserialize)]
43#[serde(deny_unknown_fields)]
44pub struct Wire {
45    pub(crate) secs_since_epoch: u64,
46    pub(crate) nanos_since_epoch: u32,
47
48    #[serde(default, skip_serializing_if = "is_false")]
49    pub(crate) before_epoch: bool,
50}
51
52/* === Enums === */
53
54/* === Traits === */
55
56/* === Implementations === */
57
58impl From<Timestamp> for Wire {
59    fn from(value: Timestamp) -> Self {
60        let (duration, before_epoch) = match value.duration_since(UNIX_EPOCH) {
61            Ok(duration) => (duration, false),
62            Err(error) => (error.duration(), true),
63        };
64
65        Self {
66            secs_since_epoch: duration.as_secs(),
67            nanos_since_epoch: duration.subsec_nanos(),
68            before_epoch,
69        }
70    }
71}
72
73impl Wire {
74    pub fn timestamp(self) -> Result<Timestamp, &'static str> {
75        if self.nanos_since_epoch >= 1_000_000_000 {
76            return Err("invalid source timestamp nanoseconds");
77        }
78        let duration = Duration::new(self.secs_since_epoch, self.nanos_since_epoch);
79        let timestamp = if self.before_epoch {
80            if duration.is_zero() {
81                return Err("invalid negative zero timestamp");
82            }
83            UNIX_EPOCH.checked_sub(duration)
84        } else {
85            UNIX_EPOCH.checked_add(duration)
86        };
87
88        timestamp.ok_or("source timestamp outside platform range")
89    }
90}
91
92/* === Public Functions === */
93
94/* === Private Functions === */
95
96fn is_false(value: &bool) -> bool {
97    !*value
98}
99
100/* === Tests === */