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 { secs_since_epoch: duration.as_secs(), nanos_since_epoch: duration.subsec_nanos(), before_epoch }
66    }
67}
68
69impl Wire {
70    pub fn timestamp(self) -> Result<Timestamp, &'static str> {
71        if self.nanos_since_epoch >= 1_000_000_000 {
72            return Err("invalid source timestamp nanoseconds");
73        }
74        let duration = Duration::new(self.secs_since_epoch, self.nanos_since_epoch);
75        let timestamp = if self.before_epoch {
76            if duration.is_zero() {
77                return Err("invalid negative zero timestamp");
78            }
79            UNIX_EPOCH.checked_sub(duration)
80        } else {
81            UNIX_EPOCH.checked_add(duration)
82        };
83
84        timestamp.ok_or("source timestamp outside platform range")
85    }
86}
87
88/* === Public Functions === */
89
90/* === Private Functions === */
91
92fn is_false(value: &bool) -> bool {
93    !*value
94}
95
96/* === Tests === */