1use crate::value::{Instant, TimeScale, Value};
29use std::collections::BTreeMap;
30
31#[derive(Debug, Clone, PartialEq)]
33pub struct ReplayTimeline {
34 pub name: String,
36 pub instants: Vec<Instant>,
38 pub payloads: Vec<Option<Value>>,
40 pub scale: TimeScale,
42}
43
44impl ReplayTimeline {
45 pub fn new(name: &str, scale: TimeScale) -> Self {
47 Self {
48 name: name.into(),
49 instants: Vec::new(),
50 payloads: Vec::new(),
51 scale,
52 }
53 }
54
55 pub fn from_secs_nanos(name: &str, scale: TimeScale, pts: &[(i64, u32)]) -> Self {
57 let mut tl = Self::new(name, scale.clone());
58 for &(secs, nanos) in pts {
59 tl.push(
60 Instant {
61 scale: scale.clone(),
62 secs,
63 nanos,
64 frame: None,
65 seal: None,
66 },
67 None,
68 );
69 }
70 tl
71 }
72
73 pub fn push(&mut self, instant: Instant, payload: Option<Value>) -> &mut Self {
75 self.instants.push(instant);
76 self.payloads.push(payload);
77 self
78 }
79
80 pub fn len(&self) -> usize {
82 self.instants.len()
83 }
84
85 pub fn is_empty(&self) -> bool {
87 self.instants.is_empty()
88 }
89
90 pub fn get(&self, idx: usize) -> Option<&Instant> {
92 self.instants.get(idx)
93 }
94
95 pub fn payload(&self, idx: usize) -> Option<&Value> {
97 self.payloads.get(idx).and_then(|p| p.as_ref())
98 }
99}
100
101#[derive(Debug, Clone)]
108pub struct ReplayClock {
109 timeline: ReplayTimeline,
110 cursor: usize,
111 exhausted_policy: ExhaustedPolicy,
113 last_instant: Option<Instant>,
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
119pub enum ExhaustedPolicy {
120 #[default]
122 RepeatLast,
123 FailClosed,
125 Loop,
127}
128
129impl ReplayClock {
130 pub fn new(timeline: ReplayTimeline) -> Self {
132 Self {
133 timeline,
134 cursor: 0,
135 exhausted_policy: ExhaustedPolicy::default(),
136 last_instant: None,
137 }
138 }
139
140 pub fn with_exhausted_policy(mut self, policy: ExhaustedPolicy) -> Self {
142 self.exhausted_policy = policy;
143 self
144 }
145
146 pub fn tick(&mut self) -> Result<Instant, String> {
150 if self.cursor < self.timeline.len() {
151 let instant = self.timeline.instants[self.cursor].clone();
152 self.last_instant = Some(instant.clone());
153 self.cursor += 1;
154 Ok(instant)
155 } else {
156 match self.exhausted_policy {
157 ExhaustedPolicy::RepeatLast => self
158 .last_instant
159 .clone()
160 .ok_or_else(|| "empty timeline".into()),
161 ExhaustedPolicy::FailClosed => {
162 Err("replay timeline exhausted (fail-closed)".into())
163 }
164 ExhaustedPolicy::Loop => {
165 if self.timeline.is_empty() {
166 return Err("empty timeline".into());
167 }
168 self.cursor = 0;
169 let instant = self.timeline.instants[0].clone();
170 self.last_instant = Some(instant.clone());
171 self.cursor = 1;
172 Ok(instant)
173 }
174 }
175 }
176 }
177
178 pub fn cursor(&self) -> usize {
180 self.cursor
181 }
182
183 pub fn len(&self) -> usize {
185 self.timeline.len()
186 }
187
188 pub fn is_exhausted(&self) -> bool {
190 self.cursor >= self.timeline.len()
191 }
192
193 pub fn current_payload(&self) -> Option<&Value> {
195 if self.cursor < self.timeline.len() {
196 self.timeline
197 .payloads
198 .get(self.cursor)
199 .and_then(|p| p.as_ref())
200 } else {
201 None
202 }
203 }
204
205 pub fn to_value(&self) -> Value {
207 let mut rec = BTreeMap::new();
208 rec.insert("name".into(), Value::String(self.timeline.name.clone()));
209 rec.insert("cursor".into(), Value::U64(self.cursor as u64));
210 rec.insert("length".into(), Value::U64(self.timeline.len() as u64));
211 rec.insert("exhausted".into(), Value::Bool(self.is_exhausted()));
212 rec.insert(
213 "exhausted_policy".into(),
214 Value::String(
215 match self.exhausted_policy {
216 ExhaustedPolicy::RepeatLast => "repeat_last",
217 ExhaustedPolicy::FailClosed => "fail_closed",
218 ExhaustedPolicy::Loop => "loop",
219 }
220 .into(),
221 ),
222 );
223 Value::Record(rec)
224 }
225}
226
227#[cfg(test)]
228mod tests {
229 use super::*;
230
231 fn make_timeline() -> ReplayTimeline {
232 ReplayTimeline::from_secs_nanos(
233 "test",
234 TimeScale::Unix,
235 &[
236 (1000, 0),
237 (1000, 500_000_000),
238 (1001, 0),
239 (1001, 500_000_000),
240 ],
241 )
242 }
243
244 #[test]
247 fn w12_timeline_basic() {
248 let tl = make_timeline();
249 assert_eq!(tl.name, "test");
250 assert_eq!(tl.len(), 4);
251 assert!(!tl.is_empty());
252 }
253
254 #[test]
255 fn w12_timeline_get() {
256 let tl = make_timeline();
257 let i0 = tl.get(0).unwrap();
258 assert_eq!(i0.secs, 1000);
259 assert_eq!(i0.nanos, 0);
260 let i1 = tl.get(1).unwrap();
261 assert_eq!(i1.nanos, 500_000_000);
262 }
263
264 #[test]
265 fn w12_timeline_empty() {
266 let tl = ReplayTimeline::new("empty", TimeScale::Unix);
267 assert!(tl.is_empty());
268 assert_eq!(tl.len(), 0);
269 }
270
271 #[test]
272 fn w12_timeline_with_payloads() {
273 let mut tl = ReplayTimeline::new("sensors", TimeScale::Monotonic);
274 tl.push(Instant::monotonic(1000), Some(Value::F64(42.0)));
275 tl.push(Instant::monotonic(2000), None);
276 assert_eq!(tl.len(), 2);
277 assert_eq!(tl.payload(0), Some(&Value::F64(42.0)));
278 assert_eq!(tl.payload(1), None);
279 }
280
281 #[test]
284 fn w12_clock_ticks_through_timeline() {
285 let mut clock = ReplayClock::new(make_timeline());
286 let i0 = clock.tick().unwrap();
287 assert_eq!(i0.secs, 1000);
288 assert_eq!(i0.nanos, 0);
289 let i1 = clock.tick().unwrap();
290 assert_eq!(i1.nanos, 500_000_000);
291 let i2 = clock.tick().unwrap();
292 assert_eq!(i2.secs, 1001);
293 assert_eq!(clock.cursor(), 3);
294 }
295
296 #[test]
297 fn w12_clock_exhausted_repeat_last() {
298 let mut clock = ReplayClock::new(make_timeline());
299 for _ in 0..4 {
301 clock.tick().unwrap();
302 }
303 assert!(clock.is_exhausted());
304 let i = clock.tick().unwrap();
306 assert_eq!(i.secs, 1001);
307 assert_eq!(i.nanos, 500_000_000);
308 }
309
310 #[test]
311 fn w12_clock_exhausted_fail_closed() {
312 let mut clock =
313 ReplayClock::new(make_timeline()).with_exhausted_policy(ExhaustedPolicy::FailClosed);
314 for _ in 0..4 {
315 clock.tick().unwrap();
316 }
317 let result = clock.tick();
318 assert!(result.is_err());
319 assert!(result.unwrap_err().contains("fail-closed"));
320 }
321
322 #[test]
323 fn w12_clock_exhausted_loop() {
324 let mut clock =
325 ReplayClock::new(make_timeline()).with_exhausted_policy(ExhaustedPolicy::Loop);
326 for _ in 0..4 {
327 clock.tick().unwrap();
328 }
329 assert!(clock.is_exhausted());
330 let i = clock.tick().unwrap();
332 assert_eq!(i.secs, 1000);
333 assert_eq!(i.nanos, 0);
334 assert_eq!(clock.cursor(), 1);
335 }
336
337 #[test]
338 fn w12_clock_empty_timeline_fails() {
339 let mut clock = ReplayClock::new(ReplayTimeline::new("empty", TimeScale::Unix));
340 let result = clock.tick();
341 assert!(result.is_err());
342 }
343
344 #[test]
345 fn w12_clock_current_payload() {
346 let mut tl = ReplayTimeline::new("sensors", TimeScale::Monotonic);
347 tl.push(Instant::monotonic(1000), Some(Value::F64(42.0)));
348 tl.push(Instant::monotonic(2000), Some(Value::F64(43.0)));
349 let mut clock = ReplayClock::new(tl);
350 assert_eq!(clock.current_payload(), Some(&Value::F64(42.0)));
352 clock.tick().unwrap();
353 assert_eq!(clock.current_payload(), Some(&Value::F64(43.0)));
355 }
356
357 #[test]
358 fn w12_clock_to_value() {
359 let mut clock = ReplayClock::new(make_timeline());
360 clock.tick().unwrap();
361 let v = clock.to_value();
362 match v {
363 Value::Record(r) => {
364 assert_eq!(r.get("name"), Some(&Value::String("test".into())));
365 assert_eq!(r.get("cursor"), Some(&Value::U64(1)));
366 assert_eq!(r.get("length"), Some(&Value::U64(4)));
367 assert_eq!(r.get("exhausted"), Some(&Value::Bool(false)));
368 }
369 _ => panic!("expected Record"),
370 }
371 }
372
373 #[test]
374 fn w12_exhausted_policy_default() {
375 assert_eq!(ExhaustedPolicy::default(), ExhaustedPolicy::RepeatLast);
376 }
377
378 #[test]
379 fn w12_clock_loop_empty_timeline_fails() {
380 let mut clock = ReplayClock::new(ReplayTimeline::new("empty", TimeScale::Unix))
381 .with_exhausted_policy(ExhaustedPolicy::Loop);
382 let result = clock.tick();
383 assert!(result.is_err());
384 }
385}