-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfixed_history.rs
More file actions
1919 lines (1735 loc) · 66.5 KB
/
fixed_history.rs
File metadata and controls
1919 lines (1735 loc) · 66.5 KB
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Fixed-size access history ring buffer.
//!
//! Stores the last `K` timestamps in a ring buffer, providing O(1) record
//! and O(1) access to the k-th most recent entry. Essential for LRU-K policies
//! where eviction decisions depend on the K-th most recent access time.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │ FixedHistory<K=4> Layout │
//! │ │
//! │ Ring Buffer │
//! │ ──────────── │
//! │ │
//! │ data: [u64; K] cursor: next write position │
//! │ len: valid entries (wraps around when full) │
//! │ │
//! │ After recording: 10, 20, 30, 40, 50 │
//! │ │
//! │ Index: 0 1 2 3 │
//! │ ┌─────┬─────┬─────┬─────┐ │
//! │ data: │ 50 │ 20 │ 30 │ 40 │ │
//! │ └─────┴─────┴─────┴─────┘ │
//! │ ▲ │
//! │ │ │
//! │ cursor = 1 (next write goes here) │
//! │ │
//! │ Access Pattern │
//! │ ────────────── │
//! │ │
//! │ kth_most_recent(k) = data[(cursor + K - k) % K] │
//! │ │
//! │ k=1 (most recent): data[(1 + 4 - 1) % 4] = data[0] = 50 │
//! │ k=2: data[(1 + 4 - 2) % 4] = data[3] = 40 │
//! │ k=3: data[(1 + 4 - 3) % 4] = data[2] = 30 │
//! │ k=4 (oldest): data[(1 + 4 - 4) % 4] = data[1] = 20 │
//! │ │
//! │ Record Flow │
//! │ ─────────── │
//! │ │
//! │ record(60): │
//! │ 1. data[cursor] = 60 → data[1] = 60 │
//! │ 2. cursor = (cursor + 1) % K → cursor = 2 │
//! │ 3. len stays at K (already full) │
//! │ │
//! └─────────────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Key Components
//!
//! - [`FixedHistory`]: Fixed-size ring buffer for timestamp history
//! - [`Iter`]: Borrowed iterator over timestamps in MRU order
//! - [`IntoIter`]: Owning iterator over timestamps in MRU order
//!
//! ## Operations
//!
//! | Operation | Description | Complexity |
//! |-----------------------|----------------------------------|------------|
//! | [`record`] | Add timestamp (overwrites oldest)| O(1) |
//! | [`most_recent`] | Get most recent timestamp | O(1) |
//! | [`kth_most_recent`] | Get k-th most recent timestamp | O(1) |
//! | [`iter`] / [`into_iter`] | Iterate in MRU order | O(K) |
//! | [`to_vec_mru`] | Collect all into a Vec (MRU) | O(K) |
//!
//! [`record`]: FixedHistory::record
//! [`most_recent`]: FixedHistory::most_recent
//! [`kth_most_recent`]: FixedHistory::kth_most_recent
//! [`iter`]: FixedHistory::iter
//! [`into_iter`]: FixedHistory#impl-IntoIterator
//! [`to_vec_mru`]: FixedHistory::to_vec_mru
//!
//! ## Use Cases
//!
//! - **LRU-K policy**: Track last K access times per entry for eviction decisions
//! - **Access frequency**: Count accesses within a time window
//! - **Temporal patterns**: Detect periodic access patterns
//!
//! ## Example Usage
//!
//! ```
//! use cachekit::ds::FixedHistory;
//!
//! // Track last 3 access times
//! let mut history = FixedHistory::<3>::new();
//!
//! // Record access timestamps
//! history.record(100);
//! history.record(200);
//! history.record(300);
//!
//! // Most recent access
//! assert_eq!(history.most_recent(), Some(300));
//!
//! // LRU-K: Get K-th most recent for eviction comparison
//! assert_eq!(history.kth_most_recent(3), Some(100)); // Oldest of K
//!
//! // Overwrites oldest when full
//! history.record(400);
//! assert_eq!(history.to_vec_mru(), vec![400, 300, 200]); // 100 is gone
//! ```
//!
//! ## Use Case: LRU-2 Eviction
//!
//! ```
//! use cachekit::ds::FixedHistory;
//!
//! // LRU-2: Evict based on 2nd most recent access time
//! struct CacheEntry {
//! value: String,
//! history: FixedHistory<2>,
//! }
//!
//! impl CacheEntry {
//! fn new(value: String, timestamp: u64) -> Self {
//! let mut entry = CacheEntry {
//! value,
//! history: FixedHistory::new(),
//! };
//! entry.history.record(timestamp);
//! entry
//! }
//!
//! fn access(&mut self, timestamp: u64) {
//! self.history.record(timestamp);
//! }
//!
//! // LRU-2 uses the 2nd most recent access for comparison
//! fn eviction_priority(&self) -> u64 {
//! // If only 1 access, use that; otherwise use 2nd most recent
//! self.history.kth_most_recent(2)
//! .or(self.history.most_recent())
//! .unwrap_or(0)
//! }
//! }
//!
//! let mut entry = CacheEntry::new("data".into(), 100);
//! assert_eq!(entry.eviction_priority(), 100); // Only 1 access
//!
//! entry.access(200);
//! assert_eq!(entry.eviction_priority(), 100); // 2nd most recent = 100
//!
//! entry.access(300);
//! assert_eq!(entry.eviction_priority(), 200); // 2nd most recent = 200
//! ```
//!
//! ## Thread Safety
//!
//! `FixedHistory` is not thread-safe. It is typically embedded within
//! cache entries and protected by the cache's synchronization.
//!
//! ## Security & Invariants
//!
//! - **Trusted timestamps.** The caller is responsible for supplying
//! monotonically non-decreasing timestamps drawn from a trusted source
//! (e.g. a coarse monotonic counter). If an adversary can influence the
//! timestamp stream — for example via a wall-clock that can jump
//! backwards, or a user-controlled counter — they can manipulate
//! LRU-K-style eviction decisions built on top of this type. See
//! [`FixedHistory::record`] for the full trust boundary.
//! - **Capacity bound.** `K` is capped at [`MAX_K`] (see [`FixedHistory::new`]).
//! This keeps the inline `[u64; K]` array from triggering stack exhaustion
//! if `K` is ever influenced by code an attacker controls. For large `K`
//! on restricted stacks, use [`FixedHistory::boxed`] to heap-allocate
//! without materialising the array on the stack.
//! - **Per-entry memory is a multiplier, not a bound.** [`MAX_K`] caps the
//! per-instance footprint at 32 KiB, not the total. If an attacker can
//! cause `N` `FixedHistory<K>` instances to be created (one per cache
//! entry, one per session, etc.) the effective heap pressure is
//! `N * size_of::<FixedHistory<K>>()`. When `K` approaches [`MAX_K`]
//! and `N` is attacker-influenced, pair this type with a hard
//! admission-control cap on the surrounding container; [`MAX_K`] alone
//! will not save you from a memory-DoS in that configuration.
//! - **No stale-slot disclosure via the public API.**
//! [`FixedHistory::clear`] overwrites the backing array with zeros and
//! the manual `Debug` impl only prints logically-live entries, so
//! overwritten or cleared timestamps cannot be observed through
//! `record` / `kth_most_recent` / `iter` / `Debug` / `PartialEq` /
//! `Hash`. This is a logical guarantee, not a memory-scrubbing one:
//! [`FixedHistory::clear`] is not a secure wipe, and `Copy` / `Clone`
//! propagate the full backing array (including stale slots beyond
//! `len`) to the new value.
//! - **Not constant-time.** [`PartialEq`] and [`std::hash::Hash`] iterate
//! only as far as the shared prefix, so they are not suitable for
//! comparing data that must remain secret. `FixedHistory` is intended for
//! access-timestamp bookkeeping, not for security-sensitive values.
//!
//! ## Implementation Notes
//!
//! - Uses a fixed-size inline array by default (no heap allocation);
//! [`FixedHistory::boxed`] is provided for heap-allocating large `K`.
//! - Const generic `K` determines history depth at compile time
//! - Zero-size history (`K=0`) is a no-op
//! - Construction is bounded by [`MAX_K`]; exceeding it is a compile-time error
//! - `debug_validate_invariants()` available in debug/test builds
//!
//! [`MAX_K`]: MAX_K
/// Upper bound on `K` for [`FixedHistory`].
///
/// `FixedHistory<K>` stores `[u64; K]` inline, so an arbitrary `K` would risk
/// stack exhaustion (especially since [`FixedHistory::new`] returns by value
/// and materialises the array on the stack before any move).
///
/// This limit is enforced at compile time by [`FixedHistory::new`] and is
/// deliberately generous: realistic LRU-K policies use `K` in the single
/// digits, so `4096` leaves multiple orders of magnitude of headroom while
/// keeping the worst-case stack footprint at 32 KiB.
pub const MAX_K: usize = 4096;
/// Fixed-size ring buffer of the last `K` timestamps.
///
/// Stores timestamps in a circular buffer, automatically overwriting the oldest
/// entry when full. Provides O(1) access to any of the last K timestamps.
///
/// Implements [`Clone`], [`Copy`], [`Debug`], [`PartialEq`], [`Eq`], [`Hash`],
/// and [`IntoIterator`]. See [`iter`](Self::iter) for borrowed iteration in MRU order.
///
/// # Type Parameters
///
/// - `K`: Maximum number of timestamps to retain (const generic)
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history = FixedHistory::<3>::new();
///
/// history.record(10);
/// history.record(20);
/// history.record(30);
///
/// assert_eq!(history.most_recent(), Some(30));
/// assert_eq!(history.kth_most_recent(2), Some(20));
/// assert_eq!(history.kth_most_recent(3), Some(10));
///
/// // When full, oldest is overwritten
/// history.record(40);
/// assert_eq!(history.to_vec_mru(), vec![40, 30, 20]);
/// ```
///
/// # Use Case: Access Frequency Window
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// // Track last 5 access times
/// let mut history = FixedHistory::<5>::new();
///
/// // Simulate accesses at various times
/// for ts in [100, 150, 180, 200, 250] {
/// history.record(ts);
/// }
///
/// // Check if accessed recently (within last 100 time units).
/// //
/// // `saturating_sub` rather than `-` because, per the module-level
/// // "trusted timestamps" docs, nothing in `FixedHistory` guarantees
/// // that recorded timestamps are monotonic relative to `now`. If the
/// // clock source can ever run backwards (wall clock, attacker-
/// // influenced counter, NTP step), a plain subtraction underflows and
/// // panics in debug / wraps to `u64::MAX - delta` in release.
/// let now = 260u64;
/// let oldest_in_window = history.kth_most_recent(5).unwrap();
/// let window_duration = now.saturating_sub(oldest_in_window);
///
/// assert_eq!(window_duration, 160); // 5 accesses over 160 time units
/// ```
// `Clone` and `Copy` are sound to derive because the backing array
// maintains a zero-tail invariant: slots outside the logically-live
// region (index `>= len` while `len < K`) are always `0`. That is
// enforced by `new` / `boxed` zero-initialising `data`, by `clear`
// re-zeroing it, and by `record` only ever writing to `data[cursor]`
// where `cursor` tracks the next live slot. `debug_validate_invariants`
// checks this explicitly in test / debug builds. The upshot is that a
// bitwise copy of `FixedHistory<K>` never carries forward stale
// timestamps, so the derived `Clone` / `Copy` cannot leak data that
// the public API would otherwise hide.
#[derive(Clone, Copy)]
pub struct FixedHistory<const K: usize> {
data: [u64; K],
len: usize,
cursor: usize,
}
// Tripwire for `FixedHistory::boxed`. The constructor below initialises
// each field individually through a typed raw pointer, so its SAFETY
// obligation is narrow — only "`u64` accepts any bit pattern" is relied
// upon. The remaining failure mode is *forgetting* to initialise a new
// field after it's added to the struct, which `assume_init` cannot
// catch on its own. This destructure pattern forces that to be a
// compile error: adding a field without listing it here fails with
// "pattern does not mention field ...". If this trips, update the
// destructure AND add a matching write in `boxed()` — do not just
// paper over the pattern.
impl<const K: usize> FixedHistory<K> {
#[allow(dead_code)]
fn _boxed_field_exhaustiveness_tripwire(s: Self) {
let Self {
data: _,
len: _,
cursor: _,
} = s;
}
}
// Manual `Debug` impl: only print the logically-live entries in MRU order,
// not the raw ring buffer. This prevents stale slots (left behind after a
// `clear()` or a wrap) from appearing in panic messages / logs, which would
// otherwise leak past access patterns that the public API already hides.
//
// Allocation-free: streams entries through `self.iter()` via a nested
// `DebugList` adapter rather than materialising a `Vec<u64>` first. This
// matters on the panic / OOM path — `Debug` is frequently invoked from
// `assert!` / `panic!` formatting, and a second allocation there can
// double-panic to abort. For `K = MAX_K` the old form allocated 32 KiB
// per `{:?}` call; this form allocates nothing.
impl<const K: usize> std::fmt::Debug for FixedHistory<K> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
struct MruList<'a, const K: usize>(&'a FixedHistory<K>);
impl<const K: usize> std::fmt::Debug for MruList<'_, K> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list().entries(self.0.iter()).finish()
}
}
f.debug_struct("FixedHistory")
.field("capacity", &K)
.field("len", &self.len)
.field("mru", &MruList(self))
.finish()
}
}
impl<const K: usize> FixedHistory<K> {
/// Creates an empty history.
///
/// # Compile-time bound
///
/// `K` must be less than or equal to [`MAX_K`]. Instantiating
/// `FixedHistory<K>` with a larger `K` fails compilation. This prevents
/// stack exhaustion from pathological `K` values and keeps the inline
/// `[u64; K]` array to a bounded size.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let history = FixedHistory::<4>::new();
/// assert!(history.is_empty());
/// assert_eq!(history.capacity(), 4);
/// ```
pub fn new() -> Self {
const {
assert!(
K <= MAX_K,
"FixedHistory<K>: K exceeds MAX_K (see cachekit::ds::fixed_history::MAX_K)"
);
}
Self {
data: [0; K],
len: 0,
cursor: 0,
}
}
/// Creates an empty history on the heap without materialising the
/// `[u64; K]` array on the stack.
///
/// For small `K` this is equivalent to `Box::new(Self::new())` and
/// slightly slower. For large `K` (up to [`MAX_K`]) the difference is
/// significant: `Self::new()` returns `Self` by value, and a naive
/// `Box::new(Self::new())` may materialise the 32 KiB array on the
/// stack before moving it to the heap. That stack copy is an
/// availability concern on restricted stacks (async tasks on small
/// runtimes, threads created with a custom stack size, `no_std`
/// targets). `boxed()` sidesteps this by zero-initialising the heap
/// allocation in place.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history: Box<FixedHistory<4096>> = FixedHistory::boxed();
/// history.record(100);
/// assert_eq!(history.most_recent(), Some(100));
/// ```
pub fn boxed() -> Box<Self> {
const {
assert!(
K <= MAX_K,
"FixedHistory<K>: K exceeds MAX_K (see cachekit::ds::fixed_history::MAX_K)"
);
}
let mut uninit: Box<std::mem::MaybeUninit<Self>> = Box::new_uninit();
// SAFETY: `uninit` is a unique, properly-aligned heap allocation
// of `MaybeUninit<Self>`. Before `assume_init` is called, every
// field of `Self` is written exactly once:
//
// * `data: [u64; K]` — the `let data_ptr: *mut [u64; K]` binding
// has an explicit type annotation. If the field's type ever
// changes (e.g. to `[NonZeroU64; K]`, which is *not* zero-valid),
// that `let` stops compiling, so the `write_bytes(_, 0, 1)`
// cannot silently zero a non-zero-valid element type. `u64`
// accepts any bit pattern, so zeroing `size_of::<[u64; K]>()`
// bytes yields a valid `[u64; K]`.
//
// * `len` and `cursor` are each written with `0_usize` through
// `addr_of_mut!(...).write(0_usize)`. If either field is
// changed to a type that does not coerce from a `usize`
// literal (e.g. `NonZeroUsize`), the `write(0_usize)` call
// stops compiling, guarding against a silent validity
// regression.
//
// * Adding a *new* field is caught at compile time by
// `_boxed_field_exhaustiveness_tripwire` above, which fails
// to compile if any field is missing from its destructure
// pattern.
//
// With all fields initialised, `assume_init` is sound.
unsafe {
let p = uninit.as_mut_ptr();
let data_ptr: *mut [u64; K] = std::ptr::addr_of_mut!((*p).data);
std::ptr::write_bytes(data_ptr, 0u8, 1);
std::ptr::addr_of_mut!((*p).len).write(0_usize);
std::ptr::addr_of_mut!((*p).cursor).write(0_usize);
uninit.assume_init()
}
}
/// Returns the maximum number of timestamps retained.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let history = FixedHistory::<5>::new();
/// assert_eq!(history.capacity(), 5);
/// ```
pub fn capacity(&self) -> usize {
K
}
/// Returns the number of timestamps currently stored (<= `K`).
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history = FixedHistory::<3>::new();
/// assert_eq!(history.len(), 0);
///
/// history.record(100);
/// history.record(200);
/// assert_eq!(history.len(), 2);
///
/// // Length caps at K
/// history.record(300);
/// history.record(400);
/// assert_eq!(history.len(), 3); // Still 3, oldest was overwritten
/// ```
pub fn len(&self) -> usize {
self.len
}
/// Returns `true` if there are no timestamps recorded.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history = FixedHistory::<3>::new();
/// assert!(history.is_empty());
///
/// history.record(100);
/// assert!(!history.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Records a timestamp, overwriting the oldest if the history is full.
///
/// # Trust boundary
///
/// `record` does **not** validate `timestamp` — it accepts any `u64`
/// and treats the most recently recorded value as "now" for the
/// purposes of LRU-K ordering. Callers are responsible for supplying
/// timestamps from a trusted source, typically a monotonic counter
/// incremented on each cache access. If an attacker can influence the
/// timestamp stream (for example, because it is derived from a
/// wall-clock that can jump, a user-supplied header, or any
/// value not under the cache's exclusive control) they can:
///
/// - Pin victim entries in cache forever by recording a far-future
/// timestamp, triggering eviction of legitimate entries (cache
/// pollution / DoS).
/// - Make victim entries look "cold" by recording stale timestamps,
/// evicting hot entries they do not own (targeted eviction / cache
/// side channel).
///
/// Store this value internally; never route it directly from network
/// input.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history = FixedHistory::<2>::new();
///
/// history.record(10);
/// history.record(20);
/// assert_eq!(history.to_vec_mru(), vec![20, 10]);
///
/// // Overwrites oldest (10)
/// history.record(30);
/// assert_eq!(history.to_vec_mru(), vec![30, 20]);
/// ```
pub fn record(&mut self, timestamp: u64) {
if K == 0 {
return;
}
// Zero-tail invariant guard: while partially filled, `cursor`
// and `len` must stay in lock-step so every slot at index
// `>= len` is still a pristine zero. The `Copy` / `Clone` safety
// story in the module docs hinges on this, and nothing in the
// release build catches a refactor that splits `record()` into
// "write first, commit `len` later" or otherwise breaks the
// lock-step. Assert at the point of change so a regression
// surfaces in debug/test runs at the offending operation, not
// only when `debug_validate_invariants` happens to be called.
debug_assert!(self.cursor < K, "cursor out of range");
debug_assert!(
self.len == K || self.cursor == self.len,
"FixedHistory zero-tail invariant broken before record(): \
cursor = {}, len = {}, K = {}",
self.cursor,
self.len,
K
);
self.data[self.cursor] = timestamp;
self.cursor = (self.cursor + 1) % K;
if self.len < K {
self.len += 1;
}
}
/// Returns the most recently recorded timestamp.
///
/// Returns `None` if the history is empty.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history = FixedHistory::<3>::new();
/// assert_eq!(history.most_recent(), None);
///
/// history.record(100);
/// history.record(200);
/// assert_eq!(history.most_recent(), Some(200));
/// ```
pub fn most_recent(&self) -> Option<u64> {
self.kth_most_recent(1)
}
/// Returns the k-th most recent timestamp (`k = 1` is most recent).
///
/// Returns `None` if `k` is 0, exceeds the number of recorded timestamps,
/// or if the history is empty.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history = FixedHistory::<4>::new();
/// history.record(10);
/// history.record(20);
/// history.record(30);
///
/// // k=1 is most recent, k=3 is oldest
/// assert_eq!(history.kth_most_recent(1), Some(30));
/// assert_eq!(history.kth_most_recent(2), Some(20));
/// assert_eq!(history.kth_most_recent(3), Some(10));
///
/// // Out of bounds
/// assert_eq!(history.kth_most_recent(0), None);
/// assert_eq!(history.kth_most_recent(4), None); // Only 3 recorded
/// ```
pub fn kth_most_recent(&self, k: usize) -> Option<u64> {
if K == 0 || k == 0 || k > self.len {
return None;
}
// Parenthesise as `cursor + (K - k)` so the intermediate stays below
// `2 * K` even for the largest permitted `K`. `k <= self.len <= K`
// guarantees `K - k` does not underflow.
let idx = (self.cursor + (K - k)) % K;
Some(self.data[idx])
}
/// Returns timestamps from most-recent to least-recent.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history = FixedHistory::<3>::new();
/// history.record(100);
/// history.record(200);
/// history.record(300);
///
/// assert_eq!(history.to_vec_mru(), vec![300, 200, 100]);
///
/// // After wrap
/// history.record(400);
/// assert_eq!(history.to_vec_mru(), vec![400, 300, 200]);
/// ```
pub fn to_vec_mru(&self) -> Vec<u64> {
(1..=self.len)
.filter_map(|k| self.kth_most_recent(k))
.collect()
}
/// Returns an iterator over recorded timestamps in MRU order (most recent first).
///
/// Does **not** consume or modify the history.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history = FixedHistory::<4>::new();
/// history.record(10);
/// history.record(20);
/// history.record(30);
///
/// let timestamps: Vec<_> = history.iter().collect();
/// assert_eq!(timestamps, vec![30, 20, 10]);
/// ```
pub fn iter(&self) -> Iter<'_, K> {
Iter {
history: self,
pos: 1,
}
}
/// Clears the history and resets cursor/length.
///
/// Zeroes the backing array so the public API, the manual `Debug`
/// impl, and derived traits (`PartialEq`, `Hash`, `IntoIterator`)
/// cannot observe previously recorded timestamps. This is a logical
/// reset for bookkeeping, **not** a secure wipe — do not rely on
/// `clear()` to scrub secret-equivalent data from memory:
///
/// - The writes are ordinary assignments through a non-volatile
/// pointer. Under `opt-level=3` / LTO, an optimiser is free to
/// elide the zeroing entirely if `clear()` is the last use of the
/// value before it is dropped or goes out of scope, because `u64`
/// has no `Drop` and no subsequent safe-code observation exists.
/// - `FixedHistory` is [`Copy`]. Any copy made before `clear()`
/// (including implicit copies through pass-by-value, `PartialEq`
/// invocations, and iterator state) still holds the original
/// timestamps; clearing one copy does not clear the others. This
/// is worse than the usual "not a secure wipe" caveat because
/// `Copy` means those copies happen *without a move at the call
/// site*.
/// - Panics between [`record`](Self::record) and `clear` leave the
/// backing array populated.
///
/// If you need a cryptographic-grade wipe (e.g. the timestamps
/// encode secret data), do not use this type. Use a dedicated
/// secret-storage type backed by [`zeroize`] or equivalent, and do
/// not derive `Copy` on it.
///
/// [`zeroize`]: https://docs.rs/zeroize
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history = FixedHistory::<3>::new();
/// history.record(10);
/// history.record(20);
///
/// history.clear();
/// assert!(history.is_empty());
/// assert_eq!(history.most_recent(), None);
/// ```
pub fn clear(&mut self) {
// `self.data.fill(0)` instead of `self.data = [0; K]`. The
// assignment form materialises a `[u64; K]` temporary on the
// stack before moving it into `self.data`, which defeats the
// point of `boxed()` for large `K`: calling `clear()` on a
// `Box<FixedHistory<MAX_K>>` would still burst 32 KiB of
// stack. `fill` writes through the existing place.
self.data.fill(0);
self.len = 0;
self.cursor = 0;
}
/// Clears the history (no heap allocations to shrink).
///
/// Equivalent to [`clear`](Self::clear) since `FixedHistory` uses
/// a fixed-size array with no heap allocation.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history = FixedHistory::<3>::new();
/// history.record(10);
///
/// history.clear_shrink();
/// assert!(history.is_empty());
/// ```
pub fn clear_shrink(&mut self) {
self.clear();
}
/// Returns an approximate memory footprint in bytes.
///
/// Since `FixedHistory` uses a fixed-size array, this is constant
/// regardless of how many timestamps are recorded.
///
/// # Caveats
///
/// Reports `size_of::<Self>()` — the payload, not the allocation.
/// When the history lives behind a [`Box`] (e.g. via
/// [`boxed`](Self::boxed)), this *does not* account for the
/// `size_of::<Box<_>>` pointer on the stack or for any allocator
/// overhead. If you are using `approx_bytes` for admission control
/// or a per-entry memory quota, add `size_of::<Box<FixedHistory<K>>>()`
/// manually for the heap-allocated form, and budget some slack for
/// allocator bookkeeping.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let history = FixedHistory::<10>::new();
/// let bytes = history.approx_bytes();
///
/// // Includes array of 10 u64s plus len and cursor
/// assert!(bytes >= 10 * std::mem::size_of::<u64>());
/// ```
pub fn approx_bytes(&self) -> usize {
std::mem::size_of::<Self>()
}
/// Returns a debug snapshot of the history in MRU order.
///
/// Only available in `cfg(test)` or `debug_assertions` builds. Not part
/// of the stable API; do not rely on this being callable from release
/// builds of downstream crates.
#[cfg(any(test, debug_assertions))]
#[doc(hidden)]
pub fn debug_snapshot_mru(&self) -> Vec<u64> {
self.to_vec_mru()
}
/// Asserts internal invariants; panics on violation.
///
/// Only available in `cfg(test)` or `debug_assertions` builds. Not part
/// of the stable API.
#[cfg(any(test, debug_assertions))]
#[doc(hidden)]
pub fn debug_validate_invariants(&self) {
assert!(self.len <= K);
if K == 0 {
assert_eq!(self.len, 0);
assert_eq!(self.cursor, 0);
} else {
assert!(self.cursor < K);
}
// Zero-tail invariant: slots outside the logically-live region
// must be zero. This is what makes the derived `Clone` / `Copy`
// safe to memcpy without leaking stale timestamps, and what
// keeps `Debug` / `PartialEq` / `Hash` from having to inspect
// the tail at all. Any code path that writes past `len` without
// updating `len`, or that returns a `FixedHistory` with
// uninitialised tail bytes, will trip this assertion.
if self.len < K {
for (i, slot) in self.data[self.len..].iter().enumerate() {
assert_eq!(
*slot,
0,
"FixedHistory zero-tail invariant violated at data[{}]",
self.len + i
);
}
}
}
}
impl<const K: usize> Default for FixedHistory<K> {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------------------
// PartialEq, Eq, Hash — compare logical content, not the raw backing array
// (raw derive would flag stale slots as differences)
// ---------------------------------------------------------------------------
/// Compares logical content in MRU order, ignoring stale slots in the
/// backing array.
///
/// # Security
///
/// This implementation is **not constant-time**: it short-circuits on the
/// first differing MRU entry, leaking the length of the matching prefix
/// through timing. `FixedHistory` is intended for access-timestamp
/// bookkeeping and is not suitable for comparing values that must remain
/// secret. Do not use it as a `HashMap` key whose timestamps are derived
/// from untrusted input without a DoS-resistant hasher (see `Hash` below).
impl<const K: usize> PartialEq for FixedHistory<K> {
fn eq(&self, other: &Self) -> bool {
if self.len != other.len {
return false;
}
for k in 1..=self.len {
if self.kth_most_recent(k) != other.kth_most_recent(k) {
return false;
}
}
true
}
}
impl<const K: usize> Eq for FixedHistory<K> {}
/// Hashes logical content in MRU order so histories with the same timestamps
/// but different internal cursor positions hash equal (consistent with
/// [`PartialEq`]).
///
/// # Security
///
/// The standard-library default hasher is randomised and DoS-resistant,
/// but this trait will cooperate with any hasher chosen by the caller.
/// If `FixedHistory` values are used as keys in a map where timestamps
/// can be influenced by an adversary (for example, wall-clock readings
/// from untrusted input), pair this type with a DoS-resistant hasher
/// rather than a fast non-cryptographic one. The contents themselves are
/// not secret-equivalent — do not rely on hashing to hide timestamps.
impl<const K: usize> std::hash::Hash for FixedHistory<K> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.len.hash(state);
for k in 1..=self.len {
self.kth_most_recent(k).hash(state);
}
}
}
// ---------------------------------------------------------------------------
// Iterator types (C-ITER-TY: names match the methods that produce them)
// ---------------------------------------------------------------------------
/// Borrowed iterator over timestamps in a [`FixedHistory`], from most recent to oldest.
///
/// Created by [`FixedHistory::iter`].
#[derive(Debug, Clone)]
pub struct Iter<'a, const K: usize> {
history: &'a FixedHistory<K>,
pos: usize, // 1-indexed: 1 = most recent, history.len() = oldest
}
impl<'a, const K: usize> Iterator for Iter<'a, K> {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
// The `?` must come *before* the increment: once the iterator is
// exhausted (pos > len), `kth_most_recent` returns `None` and we
// return without touching `pos`. This keeps `pos` bounded by
// `len + 1 <= K + 1 <= MAX_K + 1`, so the `+= 1` below cannot
// overflow no matter how many times `next()` is called after
// exhaustion. Do not reorder.
let val = self.history.kth_most_recent(self.pos)?;
self.pos += 1;
Some(val)
}
fn size_hint(&self) -> (usize, Option<usize>) {
// `saturating_sub(1)` rather than `self.pos - 1`. Today `pos`
// starts at 1 and only ever increments, so a plain subtraction
// is safe by construction — but the invariant is enforced by
// the two constructors alone. If a future refactor exposes any
// constructor (or `skip_to` / `seek` method) that can leave
// `pos == 0`, the plain form underflows in release and panics
// in debug. This form is robust-by-construction and costs a
// single instruction.
let remaining = self
.history
.len()
.saturating_sub(self.pos.saturating_sub(1));
(remaining, Some(remaining))
}
}
impl<const K: usize> ExactSizeIterator for Iter<'_, K> {}
/// Owning iterator over timestamps in a [`FixedHistory`], from most recent to oldest.
///
/// Created by calling [`IntoIterator::into_iter`] on a `FixedHistory`.
#[derive(Debug, Clone)]
pub struct IntoIter<const K: usize> {
history: FixedHistory<K>,
pos: usize,
}
impl<const K: usize> Iterator for IntoIter<K> {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
// See `Iter::next` for the invariant justifying `+= 1`: the `?`
// must remain before the increment so `pos` stays bounded once
// exhausted.
let val = self.history.kth_most_recent(self.pos)?;
self.pos += 1;
Some(val)
}
fn size_hint(&self) -> (usize, Option<usize>) {
// See `Iter::size_hint` for why `saturating_sub(1)` instead of
// `self.pos - 1`.
let remaining = self
.history
.len()
.saturating_sub(self.pos.saturating_sub(1));
(remaining, Some(remaining))
}
}
impl<const K: usize> ExactSizeIterator for IntoIter<K> {}
// ---------------------------------------------------------------------------
// IntoIterator impls (C-ITER: iter, into_iter)
// ---------------------------------------------------------------------------
impl<const K: usize> IntoIterator for FixedHistory<K> {
type Item = u64;
type IntoIter = IntoIter<K>;
/// Consumes the history, returning an iterator over timestamps in MRU order.
///
/// # Example
///
/// ```
/// use cachekit::ds::FixedHistory;
///
/// let mut history = FixedHistory::<3>::new();
/// history.record(10);
/// history.record(20);
///
/// let timestamps: Vec<_> = history.into_iter().collect();
/// assert_eq!(timestamps, vec![20, 10]);
/// ```
fn into_iter(self) -> Self::IntoIter {
IntoIter {
history: self,
pos: 1,
}
}
}
impl<'a, const K: usize> IntoIterator for &'a FixedHistory<K> {
type Item = u64;
type IntoIter = Iter<'a, K>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fixed_history_tracks_last_k() {
let mut history = FixedHistory::<3>::new();
history.record(10);
history.record(20);
history.record(30);
assert_eq!(history.to_vec_mru(), vec![30, 20, 10]);