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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
use Duration;
use crateTimeError;
/// Trait describing time-point behavior required by the transform core.
///
/// Implementing this trait allows using custom time types with
/// `Transform`, `Buffer`, and `Registry`.
///
/// The trait requires `Copy` because transform lookups and composition are hot
/// paths where timestamps are passed around frequently.
///
/// # Adapter example
///
/// If your external timestamp type does not fit this trait directly, you can
/// create a small `Copy` adapter and convert at your application boundary.
///
/// ```
/// use core::time::Duration;
/// use transforms::{errors::TimeError, time::TimePoint};
///
/// #[derive(Debug, Clone)]
/// struct ExternalTime {
/// nanos_since_epoch: u64,
/// }
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// struct CoreTime(u64);
///
/// impl From<ExternalTime> for CoreTime {
/// fn from(value: ExternalTime) -> Self {
/// Self(value.nanos_since_epoch)
/// }
/// }
///
/// impl From<CoreTime> for ExternalTime {
/// fn from(value: CoreTime) -> Self {
/// Self {
/// nanos_since_epoch: value.0,
/// }
/// }
/// }
///
/// impl TimePoint for CoreTime {
/// fn static_timestamp() -> Self {
/// Self(0)
/// }
///
/// fn duration_since(
/// self,
/// earlier: Self,
/// ) -> Result<Duration, TimeError> {
/// self.0
/// .checked_sub(earlier.0)
/// .map(Duration::from_nanos)
/// .ok_or(TimeError::DurationUnderflow)
/// }
///
/// fn checked_add(
/// self,
/// rhs: Duration,
/// ) -> Result<Self, TimeError> {
/// let rhs_ns: u64 = rhs
/// .as_nanos()
/// .try_into()
/// .map_err(|_| TimeError::DurationOverflow)?;
///
/// self.0
/// .checked_add(rhs_ns)
/// .map(Self)
/// .ok_or(TimeError::DurationOverflow)
/// }
///
/// fn checked_sub(
/// self,
/// rhs: Duration,
/// ) -> Result<Self, TimeError> {
/// let rhs_ns: u64 = rhs
/// .as_nanos()
/// .try_into()
/// .map_err(|_| TimeError::DurationOverflow)?;
///
/// self.0
/// .checked_sub(rhs_ns)
/// .map(Self)
/// .ok_or(TimeError::DurationUnderflow)
/// }
///
/// fn as_seconds(self) -> Result<f64, TimeError> {
/// Ok(self.0 as f64 / 1_000_000_000.0)
/// }
/// }
/// ```