1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// Copyright (c) 2017, 2020 ADLINK Technology Inc.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
use super::{ID, NTP64};
use std::fmt;

/// A timestamp made of a [`NTP64`] and a [`crate::HLC`]'s unique identifier.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Timestamp {
    time: NTP64,
    id: ID,
}

impl Timestamp {
    // Create a [`Timestamp`] with a [`NTP64`] and a [`crate::HLC`]'s unique `id`.
    pub fn new(time: NTP64, id: ID) -> Timestamp {
        Timestamp { time, id }
    }

    // Returns the [`NTP64`] time.
    pub fn get_time(&self) -> &NTP64 {
        &self.time
    }

    // Returns the [`crate::HLC`]'s unique `id`.
    pub fn get_id(&self) -> &ID {
        &self.id
    }
}

impl fmt::Display for Timestamp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/{}", self.time, self.id)
    }
}

impl fmt::Debug for Timestamp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}/{:?}", self.time, self.id)
    }
}

#[cfg(test)]
mod tests {
    use crate::*;
    use std::convert::TryFrom;
    use std::time::UNIX_EPOCH;

    #[test]
    fn test_timestamp() {
        let id1: ID = ID::try_from(vec![0x01].as_ref()).unwrap();
        let id2: ID = ID::try_from(vec![0x02].as_ref()).unwrap();

        let ts1_epoch = Timestamp::new(Default::default(), id1.clone());
        assert_eq!(ts1_epoch.get_time().to_system_time(), UNIX_EPOCH);
        assert_eq!(ts1_epoch.get_id(), &id1);

        let ts2_epoch = Timestamp::new(Default::default(), id2.clone());
        assert_eq!(ts2_epoch.get_time().to_system_time(), UNIX_EPOCH);
        assert_eq!(ts2_epoch.get_id(), &id2);

        // Test that 2 Timestamps with same time but different ids are different and ordered
        assert_ne!(ts1_epoch, ts2_epoch);
        assert!(ts1_epoch < ts2_epoch);

        let now = system_time_clock();
        let ts1_now = Timestamp::new(now, id1);
        let ts2_now = Timestamp::new(now, id2);
        assert_ne!(ts1_now, ts2_now);
        assert!(ts1_now < ts2_now);
        assert!(ts1_epoch < ts1_now);
        assert!(ts2_epoch < ts2_now);
    }
}