plumtree/time.rs
1//! Node local clock and time.
2use std;
3use std::ops::{Add, AddAssign};
4use std::time::Duration;
5
6/// Node local clock.
7///
8/// Each [`Node`] has a clock instance.
9/// When a node is created, the time of its clock is initialized to zero.
10/// Then each time [`Clock::tick`] method is called, the time of the clock proceeds by the specified duration.
11///
12/// [`Node`]: ../struct.Node.html
13/// [`Clock::tick`]: ./struct.Clock.html#method.tick
14#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
15pub struct Clock(Duration);
16impl Clock {
17 /// Makes a new `Clock` instance.
18 ///
19 /// # Examples
20 ///
21 /// ```
22 /// use plumtree::time::Clock;
23 /// use std::time::Duration;
24 ///
25 /// assert_eq!(Clock::new().now().as_duration(), Duration::from_secs(0));
26 /// ```
27 pub fn new() -> Self {
28 Self::default()
29 }
30
31 /// Returns the current time of the clock.
32 ///
33 /// # Examples
34 ///
35 /// ```
36 /// use plumtree::time::Clock;
37 /// use std::time::Duration;
38 ///
39 /// let mut clock = Clock::new();
40 /// assert_eq!(clock.now().as_duration(), Duration::from_secs(0));
41 ///
42 /// clock.tick(Duration::from_secs(100));
43 /// assert_eq!(clock.now().as_duration(), Duration::from_secs(100));
44 /// ```
45 pub fn now(&self) -> NodeTime {
46 NodeTime(self.0)
47 }
48
49 /// Proceeds the time of the clock by the given duration.
50 pub fn tick(&mut self, duration: Duration) {
51 self.0 += duration;
52 }
53
54 pub(crate) fn max() -> Self {
55 let max = Duration::new(std::u64::MAX, 0);
56 Clock(max)
57 }
58}
59
60/// Node local time.
61///
62/// This represents the elapsed logical time since a clock was created.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
64pub struct NodeTime(Duration);
65impl NodeTime {
66 /// Converts `NodeTime` to `Duration`.
67 pub fn as_duration(&self) -> Duration {
68 self.0
69 }
70}
71impl Add<Duration> for NodeTime {
72 type Output = Self;
73
74 fn add(self, rhs: Duration) -> Self::Output {
75 NodeTime(self.0 + rhs)
76 }
77}
78impl AddAssign<Duration> for NodeTime {
79 fn add_assign(&mut self, rhs: Duration) {
80 self.0 += rhs;
81 }
82}