1use super::LoopError;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub struct CheckpointSnapshot {
15 pub rules: u64,
16 pub index: usize,
17}
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub struct CheckpointAnchor<T> {
22 pub index: usize,
23 pub anchor: T,
24}
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub struct CheckpointRecovery<T> {
33 pub current: CheckpointAnchor<T>,
34 pub next: Option<CheckpointAnchor<T>>,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum CheckpointActivation {
40 Activated { previous_index: usize, index: usize },
42 Current { index: usize },
44 Stale { index: usize, current_index: usize },
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum CheckpointRestore {
51 Unchanged { index: usize },
53 Rewound { previous_index: usize, index: usize },
55 Advanced { previous_index: usize, index: usize },
57}
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum CheckpointRestoreError {
62 RulesMismatch { expected: u64, actual: u64 },
64 InvalidIndex { index: usize, anchor_count: usize },
66}
67
68#[derive(Clone, Copy, Debug)]
69pub struct Checkpoints<T: Copy, const N: usize> {
70 anchors: [T; N],
71 index: usize,
72 rules: u64,
73}
74impl<T: Copy, const N: usize> Checkpoints<T, N> {
75 pub fn new(rules: u64, anchors: [T; N]) -> Result<Self, LoopError> {
79 if N == 0 || N > 256 || rules == 0 {
80 return Err(LoopError::Invalid);
81 }
82 Ok(Self {
83 anchors,
84 index: 0,
85 rules,
86 })
87 }
88 pub fn index(&self) -> usize {
89 self.index
90 }
91 pub fn respawn(&self) -> T {
92 self.anchors[self.index]
93 }
94
95 pub fn current_anchor(&self) -> CheckpointAnchor<T> {
103 CheckpointAnchor {
104 index: self.index,
105 anchor: self.respawn(),
106 }
107 }
108
109 pub fn next_anchor(&self) -> Option<CheckpointAnchor<T>> {
120 let index = self.index + 1;
121 self.anchors
122 .get(index)
123 .copied()
124 .map(|anchor| CheckpointAnchor { index, anchor })
125 }
126
127 pub fn recovery(&self) -> CheckpointRecovery<T> {
142 CheckpointRecovery {
143 current: self.current_anchor(),
144 next: self.next_anchor(),
145 }
146 }
147
148 pub fn activate(&mut self, index: usize) -> Result<bool, LoopError> {
151 self.activate_with_outcome(index)
152 .map(|outcome| matches!(outcome, CheckpointActivation::Activated { .. }))
153 }
154
155 pub fn activate_with_outcome(
172 &mut self,
173 index: usize,
174 ) -> Result<CheckpointActivation, LoopError> {
175 if index >= N {
176 return Err(LoopError::Invalid);
177 }
178 if index < self.index {
179 return Ok(CheckpointActivation::Stale {
180 index,
181 current_index: self.index,
182 });
183 }
184 if index == self.index {
185 return Ok(CheckpointActivation::Current { index });
186 }
187 if index != self.index + 1 {
188 return Err(LoopError::Unavailable);
189 }
190 let previous_index = self.index;
191 self.index = index;
192 Ok(CheckpointActivation::Activated {
193 previous_index,
194 index,
195 })
196 }
197 pub fn snapshot(&self) -> CheckpointSnapshot {
198 CheckpointSnapshot {
199 rules: self.rules,
200 index: self.index,
201 }
202 }
203 pub fn restore(&mut self, saved: CheckpointSnapshot) -> Result<(), LoopError> {
206 self.restore_with_outcome(saved)
207 .map(|_| ())
208 .map_err(|_| LoopError::Invalid)
209 }
210
211 pub fn restore_with_outcome(
237 &mut self,
238 saved: CheckpointSnapshot,
239 ) -> Result<CheckpointRestore, CheckpointRestoreError> {
240 if saved.rules != self.rules {
241 return Err(CheckpointRestoreError::RulesMismatch {
242 expected: self.rules,
243 actual: saved.rules,
244 });
245 }
246 if saved.index >= N {
247 return Err(CheckpointRestoreError::InvalidIndex {
248 index: saved.index,
249 anchor_count: N,
250 });
251 }
252 let previous_index = self.index;
253 let index = saved.index;
254 let outcome = match index.cmp(&previous_index) {
255 std::cmp::Ordering::Less => CheckpointRestore::Rewound {
256 previous_index,
257 index,
258 },
259 std::cmp::Ordering::Equal => CheckpointRestore::Unchanged { index },
260 std::cmp::Ordering::Greater => CheckpointRestore::Advanced {
261 previous_index,
262 index,
263 },
264 };
265 self.index = saved.index;
266 Ok(outcome)
267 }
268}
269#[cfg(test)]
270mod tests {
271 use super::*;
272 #[test]
273 fn checkpoints_are_ordered_and_snapshots_validate_before_mutation() {
274 let mut c = Checkpoints::new(4, [10, 20, 30]).unwrap();
275 assert_eq!(c.respawn(), 10);
276 assert_eq!(c.activate(2), Err(LoopError::Unavailable));
277 assert!(c.activate(1).unwrap());
278 assert!(!c.activate(0).unwrap());
279 let saved = c.snapshot();
280 assert!(c.activate(2).unwrap());
281 c.restore(saved).unwrap();
282 assert_eq!(c.respawn(), 20);
283 assert!(
284 c.restore(CheckpointSnapshot { rules: 5, index: 0 })
285 .is_err()
286 );
287 assert_eq!(c.index(), 1);
288 assert!(
289 c.restore(CheckpointSnapshot { rules: 4, index: 3 })
290 .is_err()
291 );
292 assert_eq!(c.index(), 1);
293 }
294
295 #[test]
296 fn recovery_inspects_current_and_next_without_consuming_or_advancing() {
297 let mut c = Checkpoints::new(4, [10, 10, 30]).unwrap();
299 for index in 0..3 {
300 c.activate(index).unwrap();
301 let before = c.snapshot();
302 let current = CheckpointAnchor {
303 index,
304 anchor: [10, 10, 30][index],
305 };
306 let next = [10, 10, 30]
307 .get(index + 1)
308 .copied()
309 .map(|anchor| CheckpointAnchor {
310 index: index + 1,
311 anchor,
312 });
313 let expected = CheckpointRecovery { current, next };
314 assert_eq!(c.current_anchor(), current);
315 assert_eq!(c.next_anchor(), next);
316 assert_eq!(c.recovery(), expected);
317 assert_eq!(c.recovery(), expected);
318 assert_eq!(c.respawn(), current.anchor);
319 assert_eq!(c.snapshot(), before);
320 }
321 assert_eq!(c.recovery().current.anchor, 30);
322 assert_eq!(c.recovery().next, None);
323 }
324
325 #[test]
326 fn activation_outcomes_cover_stale_duplicate_skipped_and_terminal_triggers() {
327 for current_index in 0..4 {
328 for index in [0, 1, 2, 3, 4, usize::MAX] {
329 let mut c = Checkpoints::new(4, [10, 20, 30, 40]).unwrap();
330 c.restore(CheckpointSnapshot {
331 rules: 4,
332 index: current_index,
333 })
334 .unwrap();
335 let mut legacy = c;
336 let before = c.snapshot();
337 let expected = if index >= 4 {
338 Err(LoopError::Invalid)
339 } else if index < current_index {
340 Ok(CheckpointActivation::Stale {
341 index,
342 current_index,
343 })
344 } else if index == current_index {
345 Ok(CheckpointActivation::Current { index })
346 } else if index == current_index + 1 {
347 Ok(CheckpointActivation::Activated {
348 previous_index: current_index,
349 index,
350 })
351 } else {
352 Err(LoopError::Unavailable)
353 };
354 let accepted = expected
355 .map(|outcome| matches!(outcome, CheckpointActivation::Activated { .. }));
356 assert_eq!(c.activate_with_outcome(index), expected);
357 assert_eq!(legacy.activate(index), accepted);
358 assert_eq!(c.snapshot(), legacy.snapshot());
359 if accepted == Ok(true) {
360 assert_eq!(c.index(), index);
361 assert_eq!(c.respawn(), [10, 20, 30, 40][index]);
362 } else {
363 assert_eq!(c.snapshot(), before);
364 }
365 }
366 }
367 }
368
369 #[test]
370 fn trusted_restore_reports_rewinds_advances_and_unchanged_including_terminal() {
371 for previous_index in 0..4 {
372 for index in 0..4 {
373 let mut c = Checkpoints::new(4, [10, 20, 30, 40]).unwrap();
374 c.restore(CheckpointSnapshot {
375 rules: 4,
376 index: previous_index,
377 })
378 .unwrap();
379 let mut legacy = c;
380 let saved = CheckpointSnapshot { rules: 4, index };
381 let expected = if index < previous_index {
382 CheckpointRestore::Rewound {
383 previous_index,
384 index,
385 }
386 } else if index == previous_index {
387 CheckpointRestore::Unchanged { index }
388 } else {
389 CheckpointRestore::Advanced {
390 previous_index,
391 index,
392 }
393 };
394 assert_eq!(c.restore_with_outcome(saved), Ok(expected));
395 assert_eq!(legacy.restore(saved), Ok(()));
396 assert_eq!(c.snapshot(), saved);
397 assert_eq!(legacy.snapshot(), saved);
398 assert_eq!(c.recovery(), legacy.recovery());
399 assert_eq!(c.current_anchor().anchor, [10, 20, 30, 40][index]);
400 assert_eq!(
401 c.next_anchor().map(|a| a.index),
402 (index < 3).then_some(index + 1)
403 );
404 assert_eq!(
405 c.restore_with_outcome(saved),
406 Ok(CheckpointRestore::Unchanged { index })
407 );
408 }
409 }
410 }
411
412 #[test]
413 fn restore_errors_preserve_progress_anchors_and_fingerprint() {
414 for current_index in 0..3 {
415 let mut c = Checkpoints::new(4, [10, 20, 30]).unwrap();
416 c.restore(CheckpointSnapshot {
417 rules: 4,
418 index: current_index,
419 })
420 .unwrap();
421 let before = c.snapshot();
422 let recovery = c.recovery();
423 for saved in [
424 CheckpointSnapshot { rules: 0, index: 0 },
425 CheckpointSnapshot { rules: 5, index: 2 },
426 CheckpointSnapshot {
427 rules: 5,
428 index: usize::MAX,
429 },
430 CheckpointSnapshot { rules: 4, index: 3 },
431 CheckpointSnapshot {
432 rules: 4,
433 index: usize::MAX,
434 },
435 ] {
436 let expected = if saved.rules == 4 {
437 CheckpointRestoreError::InvalidIndex {
438 index: saved.index,
439 anchor_count: 3,
440 }
441 } else {
442 CheckpointRestoreError::RulesMismatch {
443 expected: 4,
444 actual: saved.rules,
445 }
446 };
447 assert_eq!(c.restore_with_outcome(saved), Err(expected));
448 assert_eq!(c.snapshot(), before);
449 assert_eq!(c.recovery(), recovery);
450 assert_eq!(c.restore(saved), Err(LoopError::Invalid));
451 assert_eq!(c.snapshot(), before);
452 assert_eq!(c.recovery(), recovery);
453 }
454 }
455 }
456
457 #[test]
458 fn restoring_an_earlier_save_reopens_the_next_anchor() {
459 let mut c = Checkpoints::new(4, [10, 20, 30]).unwrap();
460 c.activate(1).unwrap();
461 let old_save = c.snapshot();
462 c.activate(2).unwrap();
463 assert_eq!(c.next_anchor(), None);
464 assert_eq!(
465 c.activate_with_outcome(old_save.index),
466 Ok(CheckpointActivation::Stale {
467 index: 1,
468 current_index: 2,
469 })
470 );
471 assert_eq!(c.index(), 2);
472 assert_eq!(
473 c.restore_with_outcome(old_save),
474 Ok(CheckpointRestore::Rewound {
475 previous_index: 2,
476 index: 1,
477 })
478 );
479 assert_eq!(
480 c.next_anchor(),
481 Some(CheckpointAnchor {
482 index: 2,
483 anchor: 30
484 })
485 );
486 assert_eq!(
487 c.activate_with_outcome(2),
488 Ok(CheckpointActivation::Activated {
489 previous_index: 1,
490 index: 2,
491 })
492 );
493 }
494
495 #[test]
496 fn single_anchor_and_maximum_route_recover_at_terminal_without_wraparound() {
497 let mut single = Checkpoints::new(4, [10]).unwrap();
498 assert_eq!(single.next_anchor(), None);
499 assert_eq!(
500 single.recovery().current,
501 CheckpointAnchor {
502 index: 0,
503 anchor: 10
504 }
505 );
506 assert_eq!(
507 single.activate_with_outcome(0),
508 Ok(CheckpointActivation::Current { index: 0 })
509 );
510 assert_eq!(single.activate_with_outcome(1), Err(LoopError::Invalid));
511 assert_eq!(
512 single.restore_with_outcome(single.snapshot()),
513 Ok(CheckpointRestore::Unchanged { index: 0 })
514 );
515
516 let mut maximum = Checkpoints::new(4, std::array::from_fn::<_, 256, _>(|i| i)).unwrap();
517 for index in 1..256 {
518 assert_eq!(
519 maximum.next_anchor(),
520 Some(CheckpointAnchor {
521 index,
522 anchor: index
523 })
524 );
525 assert!(maximum.activate(index).unwrap());
526 }
527 assert_eq!(maximum.recovery().current.index, 255);
528 assert_eq!(maximum.respawn(), 255);
529 assert_eq!(maximum.next_anchor(), None);
530 assert_eq!(maximum.activate_with_outcome(256), Err(LoopError::Invalid));
531 assert_eq!(maximum.index(), 255);
532 assert!(matches!(
533 Checkpoints::<u8, 0>::new(4, []),
534 Err(LoopError::Invalid)
535 ));
536 assert!(matches!(
537 Checkpoints::new(4, [0; 257]),
538 Err(LoopError::Invalid)
539 ));
540 assert!(matches!(Checkpoints::new(0, [10]), Err(LoopError::Invalid)));
541 }
542}