Debian Codegraph @

Xtimeless/src/time/offset_time.rs

raw symbols SCIP
1 //! Code around the time aspect. Stored as a list of offsets,
2 //! each a negative offset of the next value, with the latest
3 //! value being represented in whole.
4
5 use std::time::{Duration, Instant};
6
7 /// Time stored as a bunch of offsets.
8 #[derive(Default, Clone, Debug)]
9 pub struct OffsetTimeList {
10 time_offsets: Vec<u32>,
11 checkpoints: Vec<(Instant, usize)>,
12 current_time: Option<Instant>,
13 }
14
15 impl OffsetTimeList {
16 /// Create a [`OffsetTimeList`] with a capacity pre-initialized.
17 pub fn with_capacity(capacity: usize) -> Self {
18 Self::with_both_capacity(capacity, 0)
19 }
20
21 /// Create a [`OffsetTimeList`] with both time storage and
22 /// checkpoint capacity pre-initialized.
23 pub fn with_both_capacity(time_capacity: usize, checkpoint_capacity: usize) -> Self {
24 Self {
25 time_offsets: Vec::with_capacity(time_capacity),
26 checkpoints: Vec::with_capacity(checkpoint_capacity),
27 current_time: None,
28 }
29 }
30
31 /// Add a time entry. This will return the current index,
32 /// which can be used to update any [`crate::data::Data`] entries
33 /// that are corresponding to this [`OffsetTimeList`].
34 pub fn add(&mut self, time: Instant) -> usize {
35 if let Some(current_time) = self.current_time {
36 let offset = time.duration_since(current_time).as_millis() as u32;
37 self.current_time = Some(time);
38 self.time_offsets.push(offset);
39
40 // The current "index" is the length of the vec - 1, but we
41 // add back 1 since we store the current head as a separate instant.
42 self.time_offsets.len()
43 } else {
44 self.current_time = Some(time);
45
46 1
47 }
48 }
49
50 /// Add a "checkpoint"; this is used for pruning by time.
51 pub fn checkpoint(&mut self) {
52 if let Some(current_time) = self.current_time {
53 self.checkpoints
54 .push((current_time, self.time_offsets.len()));
55 }
56 }
57
58 /// Approximately prune time values older than the given [`Duration`],
59 /// and returns the new index.
60 pub fn prune(&mut self, max_age: Duration) -> Option<usize> {
61 if let Some(current_time) = self.current_time {
62 let checkpoint_index = match self.checkpoints.binary_search_by(|(instant, _)| {
63 println!(
64 "current time duration since: {:?}",
65 current_time.duration_since(*instant)
66 );
67 current_time.duration_since(*instant).cmp(&max_age)
68 }) {
69 Ok(index) | Err(index) => index,
70 };
71
72 let checkpoint_index =
73 std::cmp::min(checkpoint_index, self.checkpoints.len().saturating_sub(1));
74
75 match self.checkpoints.drain(..checkpoint_index).last() {
76 Some((_, index)) => {
77 if index < self.time_offsets.len() {
78 self.time_offsets.drain(..index);
79 Some(self.time_offsets.len())
80 } else {
81 self.time_offsets.clear();
82 self.current_time = None;
83 Some(0)
84 }
85 }
86 None => None,
87 }
88 } else {
89 None
90 }
91 }
92 }
93
94 #[cfg(test)]
95 mod tests {
96 use super::*;
97
98 #[test]
99 fn test_add() {
100 let mut times = OffsetTimeList::default();
101
102 let now = Instant::now();
103 times.add(now);
104
105 assert_eq!(times.current_time, Some(now));
106
107 let next = now + Duration::from_millis(1);
108 times.add(next);
109
110 assert_eq!(times.current_time, Some(next));
111 assert_eq!(times.time_offsets, vec!(1));
112 }
113
114 #[test]
115 fn test_prune() {
116 let mut times = OffsetTimeList::default();
117
118 // Test fully empty.
119 assert_eq!(times.prune(Duration::from_secs(0)), None);
120
121 let now = Instant::now();
122 times.add(now);
123
124 // Test no checkpoint.
125 assert_eq!(times.prune(Duration::from_secs(0)), None);
126
127 // Add a checkpoint, try clearing it.
128 times.add(now);
129 times.checkpoint();
130
131 assert_eq!(times.prune(Duration::from_secs(1000)), Some(1));
132 assert_eq!(times.prune(Duration::from_secs(0)), None);
133 }
134 }