-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathghost_list.rs
More file actions
2418 lines (2151 loc) · 80.6 KB
/
ghost_list.rs
File metadata and controls
2418 lines (2151 loc) · 80.6 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
//! Bounded recency list for ghost entries.
//!
//! Used by adaptive policies (ARC/2Q-style) to track recently evicted keys
//! without storing values. Implemented as an [`IntrusiveList`]
//! plus a `HashMap` index for O(1) lookups.
//!
//! ## Architecture
//!
//! ```text
//! ┌───────────────────────────────────────────────────────────────────────────┐
//! │ GhostList Layout │
//! │ │
//! │ ┌─────────────────────────────┐ ┌─────────────────────────────────┐ │
//! │ │ index: HashMap<K, SlotId> │ │ list: IntrusiveList<K> │ │
//! │ │ │ │ │ │
//! │ │ ┌───────────┬──────────┐ │ │ head ──► [A] ◄──► [B] ◄──► [C] │ │
//! │ │ │ Key │ SlotId │ │ │ MRU LRU │ │
//! │ │ ├───────────┼──────────┤ │ │ ▲ │ │
//! │ │ │ "key_a" │ id_0 │───┼───┼─────────► [A] │ │ │
//! │ │ │ "key_b" │ id_1 │───┼───┼─────────► [B] │ │ │
//! │ │ │ "key_c" │ id_2 │───┼───┼─────────► [C] ◄─────────────┘ │ │
//! │ │ └───────────┴──────────┘ │ │ tail │ │
//! │ └─────────────────────────────┘ └─────────────────────────────────┘ │
//! │ │
//! │ Record Flow (capacity = 3) │
//! │ ────────────────────────────── │
//! │ │
//! │ record("key_d") when full: │
//! │ 1. Check index: "key_d" not found │
//! │ 2. At capacity: evict LRU ("key_c") │
//! │ - pop_back() from list │
//! │ - remove("key_c") from index │
//! │ 3. Insert "key_d" at front (MRU) │
//! │ - push_front("key_d") in list │
//! │ - insert("key_d", id) in index │
//! │ │
//! │ record("key_a") when present: │
//! │ 1. Check index: "key_a" found with id_0 │
//! │ 2. move_to_front(id_0) in list │
//! │ 3. Done (no eviction needed) │
//! │ │
//! └───────────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Key Components
//!
//! - [`GhostList`]: Bounded recency tracker for evicted keys
//! - [`Iter`]: Iterator over keys in MRU to LRU order; created by [`GhostList::iter`]
//! - [`IntoIter`]: Consuming iterator over keys; created by `.into_iter()`
//!
//! ## Operations
//!
//! | Operation | Description | Complexity |
//! |----------------|---------------------------------------|------------|
//! | [`record`](GhostList::record) | Add/promote key to MRU, evict if full | O(1) avg |
//! | [`remove`](GhostList::remove) | Remove key from ghost list | O(1) avg |
//! | [`contains`](GhostList::contains) | Check if key is tracked | O(1) avg |
//! | [`evict_lru`](GhostList::evict_lru) | Pop the least recently used key | O(1) avg |
//! | [`record_batch`](GhostList::record_batch) | Record multiple keys | O(n) |
//! | [`remove_batch`](GhostList::remove_batch) | Remove multiple keys | O(n) |
//! | [`iter`](GhostList::iter) | Iterate keys in MRU to LRU order | O(n) |
//!
//! ## Use Cases
//!
//! - **ARC policy**: Track B1 (recently evicted once) and B2 (recently evicted twice)
//! - **2Q policy**: Track ghost entries from A1out queue
//! - **Adaptive tuning**: Detect re-references to recently evicted keys
//!
//! ## Example Usage
//!
//! ```
//! use cachekit::ds::GhostList;
//!
//! // Track last 100 evicted keys
//! let mut ghost = GhostList::new(100);
//!
//! // Record evicted keys
//! ghost.record("page_1");
//! ghost.record("page_2");
//! ghost.record("page_3");
//!
//! // Check if a key was recently evicted (ghost hit)
//! if ghost.contains(&"page_1") {
//! // Key was recently evicted - consider increasing cache size
//! println!("Ghost hit! Should have kept page_1");
//! }
//!
//! // Re-recording moves to MRU position
//! ghost.record("page_1"); // Now page_1 is most recent
//! ```
//!
//! ## Use Case: ARC-Style Adaptation
//!
//! ```
//! use cachekit::ds::GhostList;
//!
//! struct AdaptiveCache {
//! ghost_recent: GhostList<String>, // B1: recently evicted from recency list
//! ghost_frequent: GhostList<String>, // B2: recently evicted from frequency list
//! p: usize, // Adaptation parameter
//! }
//!
//! impl AdaptiveCache {
//! fn new(capacity: usize) -> Self {
//! Self {
//! ghost_recent: GhostList::new(capacity),
//! ghost_frequent: GhostList::new(capacity),
//! p: capacity / 2,
//! }
//! }
//!
//! fn on_miss(&mut self, key: String) {
//! if self.ghost_recent.contains(&key) {
//! // Hit in B1: increase recency preference
//! self.p = self.p.saturating_add(1);
//! self.ghost_recent.remove(&key);
//! } else if self.ghost_frequent.contains(&key) {
//! // Hit in B2: increase frequency preference
//! self.p = self.p.saturating_sub(1);
//! self.ghost_frequent.remove(&key);
//! }
//! }
//! }
//!
//! let mut cache = AdaptiveCache::new(100);
//! cache.ghost_recent.record("evicted_key".to_string());
//! cache.on_miss("evicted_key".to_string()); // Adapts based on ghost hit
//! ```
//!
//! ## Thread Safety
//!
//! `GhostList` is not thread-safe. For concurrent use, wrap in
//! `parking_lot::RwLock` or similar synchronization primitive.
//!
//! ## Security
//!
//! The default hasher is [`rustc_hash::FxBuildHasher`], chosen for speed on
//! trusted input. **`FxHash` is non-cryptographic and is not resistant to
//! hash-flooding / HashDoS attacks.** If a `GhostList` may observe keys
//! derived from untrusted input (for example, cache keys sourced from
//! HTTP URLs, user IDs, or request parameters), callers should either:
//!
//! - construct it with a DoS-resistant hasher via
//! [`GhostList::with_hasher`] / [`GhostList::with_capacity_and_hasher`]
//! (e.g. [`std::collections::hash_map::RandomState`]), or
//! - preprocess keys into a form the attacker cannot control the hash of.
//!
//! `GhostList` also rejects pathologically large capacities. [`GhostList::new`]
//! silently clamps `capacity` to [`GhostList::MAX_CAPACITY`] to prevent a
//! single oversized construction from aborting the process with an allocator
//! error (for example, if `capacity` is derived from untrusted configuration).
//! Use [`GhostList::try_new`] to detect the clamp explicitly.
//!
//! ## Implementation Notes
//!
//! - Backed by [`IntrusiveList`] for O(1) reordering
//! - Keys are stored in both the list and index (requires `Clone`)
//! - Zero-capacity ghost lists are no-ops (record does nothing)
//! - `K`'s `Hash`, `Eq`, and `Clone` impls must be mutually consistent:
//! `a == b` implies `hash(a) == hash(b)`, and `a.clone() == a`. Violating
//! this contract can leave a permanent, unreachable node in the internal
//! arena (memory leak for the lifetime of the ghost list).
//! - `debug_validate_invariants()` available in debug/test builds
//!
use rustc_hash::FxBuildHasher;
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash};
use crate::ds::intrusive_list::IntrusiveList;
use crate::ds::slot_arena::SlotId;
/// Bounded recency list of keys (no values), typically for ARC-style ghost tracking.
///
/// Tracks recently evicted keys to detect when items should have been kept in cache.
/// When a "ghost hit" occurs (accessing a key in the ghost list), adaptive policies
/// can adjust their behavior.
///
/// # Type Parameters
///
/// - `K`: Key type, must be `Eq + Hash + Clone`
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost = GhostList::new(3);
///
/// // Record evicted keys
/// ghost.record("a");
/// ghost.record("b");
/// ghost.record("c");
/// assert_eq!(ghost.len(), 3);
///
/// // At capacity, oldest is evicted
/// ghost.record("d");
/// assert!(!ghost.contains(&"a")); // "a" was evicted
/// assert!(ghost.contains(&"d")); // "d" is now tracked
///
/// // Re-recording promotes to MRU
/// ghost.record("b");
/// ghost.record("e");
/// assert!(ghost.contains(&"b")); // "b" survives (was promoted)
/// assert!(!ghost.contains(&"c")); // "c" was LRU, evicted
/// ```
///
/// # Use Case: Detecting Thrashing
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost = GhostList::new(50);
/// let mut ghost_hits = 0;
///
/// // Simulate evictions and re-accesses
/// let evicted_keys = vec!["key_1", "key_2", "key_3"];
/// for key in &evicted_keys {
/// ghost.record(*key);
/// }
///
/// // Later, check if we're re-accessing evicted keys
/// let accessed = vec!["key_1", "key_5", "key_2"];
/// for key in &accessed {
/// if ghost.contains(key) {
/// ghost_hits += 1;
/// // Could signal need for larger cache
/// }
/// }
///
/// assert_eq!(ghost_hits, 2); // key_1 and key_2 were ghost hits
/// ```
///
/// # Traits
///
/// Implements [`Clone`], [`PartialEq`], [`Eq`], [`Default`], [`Extend<K>`](Extend),
/// [`FromIterator<K>`](FromIterator), and [`IntoIterator`] (consuming and borrowed).
pub struct GhostList<K, S = FxBuildHasher> {
list: IntrusiveList<K>,
index: HashMap<K, SlotId, S>,
capacity: usize,
}
impl<K, S> std::fmt::Debug for GhostList<K, S> {
/// Prints only structural metadata (`capacity` and `len`) — **not** the
/// stored keys.
///
/// Cache keys in real deployments frequently embed user identifiers,
/// session tokens, URLs with sensitive query strings, or other PII.
/// Echoing the full key list into logs, panic messages, or crash
/// reports via `{:?}` would turn a benign observability statement
/// into an information-disclosure surface. Callers who genuinely need
/// to inspect keys should use [`GhostList::iter`] or, in debug builds,
/// [`GhostList::debug_snapshot_keys`] and format the result
/// explicitly.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GhostList")
.field("capacity", &self.capacity)
.field("len", &self.list.len())
.finish_non_exhaustive()
}
}
impl<K, S> Clone for GhostList<K, S>
where
K: Eq + Hash + Clone,
S: BuildHasher + Clone,
{
fn clone(&self) -> Self {
let alloc = self.list.len().min(self.capacity);
let mut new_list = IntrusiveList::with_capacity(alloc);
let mut new_index = HashMap::with_capacity_and_hasher(alloc, self.index.hasher().clone());
for (_, key) in self.list.iter_entries() {
let id = new_list.push_back(key.clone());
new_index.insert(key.clone(), id);
}
Self {
list: new_list,
index: new_index,
capacity: self.capacity,
}
}
}
/// Iterator over keys in a [`GhostList`], yielding references in MRU to LRU order.
///
/// Created by [`GhostList::iter`].
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost = GhostList::new(3);
/// ghost.record("a");
/// ghost.record("b");
///
/// let mut iter = ghost.iter();
/// assert_eq!(iter.next(), Some(&"b"));
/// assert_eq!(iter.next(), Some(&"a"));
/// assert_eq!(iter.next(), None);
/// ```
pub struct Iter<'a, K> {
inner: MapToKey<'a, K>,
}
type MapToKey<'a, K> = std::iter::Map<
crate::ds::intrusive_list::IntrusiveListEntryIter<'a, K>,
fn((SlotId, &'a K)) -> &'a K,
>;
impl<'a, K: std::fmt::Debug> std::fmt::Debug for Iter<'a, K> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Iter").finish_non_exhaustive()
}
}
impl<'a, K> Iterator for Iter<'a, K> {
type Item = &'a K;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<'a, K> ExactSizeIterator for Iter<'a, K> {}
impl<'a, K> std::iter::FusedIterator for Iter<'a, K> {}
/// Consuming iterator over keys in a [`GhostList`], yielding owned keys in MRU to LRU order.
///
/// Created by calling `.into_iter()` on a `GhostList`.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost = GhostList::new(3);
/// ghost.record("a");
/// ghost.record("b");
///
/// let keys: Vec<_> = ghost.into_iter().collect();
/// assert_eq!(keys, vec!["b", "a"]);
/// ```
#[derive(Debug)]
pub struct IntoIter<K> {
inner: std::vec::IntoIter<K>,
}
impl<K> Iterator for IntoIter<K> {
type Item = K;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K> ExactSizeIterator for IntoIter<K> {}
impl<K> std::iter::FusedIterator for IntoIter<K> {}
impl<K, S> IntoIterator for GhostList<K, S>
where
K: Eq + Hash + Clone,
S: BuildHasher,
{
type Item = K;
type IntoIter = IntoIter<K>;
/// Consumes the ghost list and yields keys in MRU to LRU order.
fn into_iter(self) -> Self::IntoIter {
let keys: Vec<K> = self.list.iter_entries().map(|(_, k)| k.clone()).collect();
IntoIter {
inner: keys.into_iter(),
}
}
}
impl<'a, K, S> IntoIterator for &'a GhostList<K, S>
where
K: Eq + Hash + Clone,
S: BuildHasher,
{
type Item = &'a K;
type IntoIter = Iter<'a, K>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<K, S> PartialEq for GhostList<K, S>
where
K: Eq + Hash + Clone,
S: BuildHasher,
{
fn eq(&self, other: &Self) -> bool {
self.capacity == other.capacity
&& self.len() == other.len()
&& self.iter().zip(other.iter()).all(|(a, b)| a == b)
}
}
impl<K, S> Eq for GhostList<K, S>
where
K: Eq + Hash + Clone,
S: BuildHasher,
{
}
impl<K, S> Extend<K> for GhostList<K, S>
where
K: Eq + Hash + Clone,
S: BuildHasher,
{
fn extend<I: IntoIterator<Item = K>>(&mut self, iter: I) {
for key in iter {
self.record(key);
}
}
}
impl<K, S> FromIterator<K> for GhostList<K, S>
where
K: Eq + Hash + Clone,
S: BuildHasher + Default,
{
/// Collects keys into a ghost list whose capacity equals the number of unique keys.
///
/// Duplicate keys are promoted rather than inserted twice, so the resulting
/// length may be less than the iterator length.
///
/// The capacity used during collection is clamped to
/// [`GhostList::MAX_CAPACITY`], which protects against iterators that
/// report a pathologically large `size_hint` lower bound.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let ghost: GhostList<&str> = ["a", "b", "c", "b"].into_iter().collect();
/// assert_eq!(ghost.len(), 3);
/// assert!(ghost.contains(&"a"));
/// ```
fn from_iter<I: IntoIterator<Item = K>>(iter: I) -> Self {
let iter = iter.into_iter();
let (lower, _) = iter.size_hint();
// Cap the initial allocation to avoid a hostile `size_hint` triggering
// an oversized preallocation (OOM DoS vector).
let initial = lower.clamp(16, Self::MAX_CAPACITY);
let mut ghost = Self::with_capacity_and_hasher(initial, S::default());
for key in iter {
ghost.record(key);
}
ghost.capacity = ghost.len();
ghost
}
}
impl<K> GhostList<K, FxBuildHasher>
where
K: Eq + Hash + Clone,
{
/// Creates a new ghost list with a maximum of `capacity` keys, using the
/// default [`FxBuildHasher`].
///
/// A capacity of 0 creates a no-op ghost list that ignores all records.
///
/// `capacity` is silently clamped to [`Self::MAX_CAPACITY`] to prevent a
/// single oversized construction from aborting the process with an
/// allocator error when the value is derived from untrusted input. Use
/// [`Self::try_new`] if you want to detect the clamp explicitly.
///
/// **Security note:** the default hasher (`FxBuildHasher`) is fast but
/// not DoS-resistant. When keys may be attacker-influenced, construct
/// with [`Self::with_capacity_and_hasher`] using
/// [`std::collections::hash_map::RandomState`] or another
/// cryptographically-randomised hasher instead. See the
/// [module-level security notes](self).
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let ghost: GhostList<String> = GhostList::new(100);
/// assert_eq!(ghost.capacity(), 100);
/// assert!(ghost.is_empty());
/// ```
pub fn new(capacity: usize) -> Self {
Self::with_capacity_and_hasher(capacity, FxBuildHasher)
}
/// Creates a new ghost list, returning an error if `capacity` exceeds
/// [`Self::MAX_CAPACITY`].
///
/// Prefer this over [`Self::new`] when `capacity` is user-supplied and
/// you want to reject oversized requests rather than silently clamp.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let ghost: GhostList<String> = GhostList::try_new(100).unwrap();
/// assert_eq!(ghost.capacity(), 100);
///
/// assert!(GhostList::<String>::try_new(usize::MAX).is_err());
/// ```
pub fn try_new(capacity: usize) -> Result<Self, CapacityOverflowError> {
Self::try_with_capacity_and_hasher(capacity, FxBuildHasher)
}
}
/// Returned by [`GhostList::try_new`] and
/// [`GhostList::try_with_capacity_and_hasher`] when the requested capacity
/// exceeds [`GhostList::MAX_CAPACITY`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CapacityOverflowError {
/// Capacity requested by the caller.
pub requested: usize,
/// Hard maximum enforced by [`GhostList`].
pub max: usize,
}
impl std::fmt::Display for CapacityOverflowError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"GhostList capacity {} exceeds maximum of {}",
self.requested, self.max
)
}
}
impl std::error::Error for CapacityOverflowError {}
impl<K, S> Default for GhostList<K, S>
where
K: Eq + Hash + Clone,
S: BuildHasher + Default,
{
/// Creates an empty ghost list with zero capacity (no-op mode).
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let ghost: GhostList<String> = GhostList::default();
/// assert_eq!(ghost.capacity(), 0);
/// assert!(ghost.is_empty());
/// ```
fn default() -> Self {
Self::with_capacity_and_hasher(0, S::default())
}
}
impl<K, S> GhostList<K, S>
where
K: Eq + Hash + Clone,
S: BuildHasher,
{
/// Upper bound on the capacity accepted by [`Self::new`],
/// [`Self::with_hasher`], and [`Self::with_capacity_and_hasher`].
///
/// Capacities larger than this are clamped. This is a defense-in-depth
/// guard that prevents a single construction call from triggering an
/// allocator abort when `capacity` is derived from untrusted input.
///
/// The value is derived at compile time from `size_of::<K>()` and the
/// target's pointer width, so the backing `Vec` allocations cannot
/// themselves overflow `isize::MAX` bytes on any supported target, and
/// the total byte footprint of a single `GhostList` cannot exceed a
/// fixed platform-independent budget.
///
/// The computation is:
///
/// - A per-entry byte cost is assembled from two sources whose values
/// are exact at compile time for the chosen `K`:
/// - the intrusive-list arena's [`IntrusiveList::BYTES_PER_ENTRY`],
/// which bundles `Option<Node<K>>`, the per-slot generation, and a
/// worst-case free-list entry; and
/// - the hash-map's per-bucket cost of `size_of::<(K, SlotId)>() + 1`
/// (one control byte per bucket), multiplied by a worst-case
/// [load-factor inflation](#load-factor-multiplier) of `3`.
/// - A byte budget is chosen as the smaller of:
/// - 16 GiB (a hard cap on any single construction), and
/// - `isize::MAX / 4` (leaving a 4× safety margin on smaller
/// pointer widths so that both backing allocations plus a
/// transient rehash-time doubling all fit in address space).
/// - `MAX_CAPACITY` is `byte_budget / per_entry`.
///
/// <a id="load-factor-multiplier"></a>
/// **Load-factor multiplier.** `hashbrown` rounds the bucket count up
/// to the next power of two sized for a 7/8 target load factor, so the
/// backing allocation at capacity `N` can be as large as
/// `(N * 8 / 7 + 1).next_power_of_two()` buckets. The worst-case
/// inflation ratio is `16/7 ≈ 2.29` (achieved when `N * 8 / 7`
/// narrowly exceeds a power of two); we round that up to `3` so the
/// arithmetic stays integer and the clamp remains conservative against
/// future load-factor changes in `hashbrown`.
///
/// Worked examples (64-bit target, 16 GiB budget):
///
/// - `K = u32` → `MAX_CAPACITY` ≈ 135 M.
/// - `K = [u8; 4096]` → `MAX_CAPACITY` ≈ 1.04 M.
pub const MAX_CAPACITY: usize = {
// `hashbrown` rounds bucket counts up to a power of two sized for a
// 7/8 load factor. Worst-case blowup is 16/7; round to 3 so the
// arithmetic is exact and the clamp stays conservative.
const HASHMAP_LOAD_FACTOR_MULTIPLIER: usize = 3;
// Exact, compile-time-known per-entry footprint of each container.
// These are sourced directly from the backing types' layouts so
// they track any future change to `Node<K>`, `SlotId`, or
// `hashbrown`'s bucket format.
let list_per_entry = IntrusiveList::<K>::BYTES_PER_ENTRY;
let bucket_bytes = std::mem::size_of::<(K, SlotId)>().saturating_add(1);
let index_per_entry = bucket_bytes.saturating_mul(HASHMAP_LOAD_FACTOR_MULTIPLIER);
let per_entry = list_per_entry.saturating_add(index_per_entry);
// Hard ceiling on any single construction: 16 GiB. Anything larger
// than this is almost certainly a misconfiguration or adversarial
// input — legitimate ghost lists are 6+ orders of magnitude smaller.
// Compute in u64 so the literal fits on 32-bit targets, then
// saturate back into usize.
let sixteen_gib_u64: u64 = 16 * 1024 * 1024 * 1024;
let sixteen_gib: usize = if sixteen_gib_u64 <= usize::MAX as u64 {
sixteen_gib_u64 as usize
} else {
usize::MAX
};
// Address-space-relative budget: 1/4 of `isize::MAX` so that both
// the arena and the hash map can be resident simultaneously and
// still briefly double their backing storage during a rehash
// without exhausting address space. Matters on 32-bit.
let isize_quarter = (isize::MAX as usize) / 4;
let byte_budget = if sixteen_gib < isize_quarter {
sixteen_gib
} else {
isize_quarter
};
byte_budget / if per_entry == 0 { 1 } else { per_entry }
};
/// Creates a new ghost list with the given hasher and capacity clamped to
/// [`Self::MAX_CAPACITY`].
///
/// Use this constructor to install a DoS-resistant hasher (e.g.
/// [`std::collections::hash_map::RandomState`]) when keys may be
/// attacker-influenced; see the [module-level security notes](self).
pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> Self {
let capacity = capacity.min(Self::MAX_CAPACITY);
Self {
list: IntrusiveList::with_capacity(capacity),
index: HashMap::with_capacity_and_hasher(capacity, hasher),
capacity,
}
}
/// Creates a new ghost list with the given hasher, returning an error if
/// `capacity` exceeds [`Self::MAX_CAPACITY`].
///
/// This is the fallible counterpart to [`Self::with_capacity_and_hasher`]
/// and the hasher-aware counterpart to [`Self::try_new`]. Prefer it when
/// `capacity` is user-supplied and you want to reject oversized requests
/// rather than silently clamp — particularly in combination with a
/// DoS-resistant hasher, where the caller is already handling untrusted
/// input.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
/// use std::collections::hash_map::RandomState;
///
/// let ghost: GhostList<String, RandomState> =
/// GhostList::try_with_capacity_and_hasher(100, RandomState::new()).unwrap();
/// assert_eq!(ghost.capacity(), 100);
///
/// assert!(
/// GhostList::<String, RandomState>::try_with_capacity_and_hasher(
/// usize::MAX,
/// RandomState::new(),
/// )
/// .is_err()
/// );
/// ```
pub fn try_with_capacity_and_hasher(
capacity: usize,
hasher: S,
) -> Result<Self, CapacityOverflowError> {
if capacity > Self::MAX_CAPACITY {
return Err(CapacityOverflowError {
requested: capacity,
max: Self::MAX_CAPACITY,
});
}
Ok(Self::with_capacity_and_hasher(capacity, hasher))
}
/// Creates a new ghost list with the given hasher and zero capacity.
///
/// The list is a no-op until further methods (there are none today) grow
/// its capacity. Provided primarily for symmetry with
/// [`std::collections::HashMap::with_hasher`].
pub fn with_hasher(hasher: S) -> Self {
Self::with_capacity_and_hasher(0, hasher)
}
/// Returns the configured capacity.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let ghost: GhostList<&str> = GhostList::new(50);
/// assert_eq!(ghost.capacity(), 50);
/// ```
pub fn capacity(&self) -> usize {
self.capacity
}
/// Returns the number of keys currently tracked.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost = GhostList::new(10);
/// assert_eq!(ghost.len(), 0);
///
/// ghost.record("a");
/// ghost.record("b");
/// assert_eq!(ghost.len(), 2);
///
/// // Re-recording same key doesn't increase length
/// ghost.record("a");
/// assert_eq!(ghost.len(), 2);
/// ```
pub fn len(&self) -> usize {
self.list.len()
}
/// Returns `true` if there are no keys tracked.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost: GhostList<&str> = GhostList::new(10);
/// assert!(ghost.is_empty());
///
/// ghost.record("key");
/// assert!(!ghost.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
/// Returns `true` if `key` is present in the ghost list.
///
/// This is the "ghost hit" check used by adaptive policies.
///
/// # Complexity
///
/// O(1) average case, O(n) worst case due to hash collisions.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost = GhostList::new(10);
/// ghost.record("evicted_page");
///
/// // Check for ghost hit
/// if ghost.contains(&"evicted_page") {
/// println!("Ghost hit! Key was recently evicted.");
/// }
///
/// assert!(ghost.contains(&"evicted_page"));
/// assert!(!ghost.contains(&"never_seen"));
/// ```
pub fn contains(&self, key: &K) -> bool {
self.index.contains_key(key)
}
/// Records `key` as most-recently-seen, evicting the least recent if needed.
///
/// If the key is already present, it is promoted to MRU position and returns `None`.
/// If at capacity, the LRU key is evicted before inserting and returned.
///
/// # Returns
///
/// - `Some(evicted_key)` if a key was evicted to make room
/// - `None` if the key was already present (promoted) or capacity not reached
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost = GhostList::new(2);
///
/// assert_eq!(ghost.record("a"), None); // No eviction
/// assert_eq!(ghost.record("b"), None); // No eviction
/// assert!(ghost.contains(&"a"));
/// assert!(ghost.contains(&"b"));
///
/// // At capacity: "a" is LRU, will be evicted
/// assert_eq!(ghost.record("c"), Some("a")); // Returns evicted key
/// assert!(!ghost.contains(&"a")); // Evicted
/// assert!(ghost.contains(&"b"));
/// assert!(ghost.contains(&"c"));
///
/// // Re-recording "b" promotes it to MRU (no eviction)
/// assert_eq!(ghost.record("b"), None); // Already present
/// assert_eq!(ghost.record("d"), Some("c")); // Evicts "c"
/// assert!(ghost.contains(&"b")); // Survived (was MRU)
/// assert!(!ghost.contains(&"c")); // Evicted (was LRU)
/// ```
pub fn record(&mut self, key: K) -> Option<K> {
if self.capacity == 0 {
return None;
}
if let Some(&id) = self.index.get(&key) {
self.list.move_to_front(id);
return None;
}
// Reserve index capacity *before* mutating the list so that an
// allocation failure here cannot leave the list containing a node
// that the index never learns about (which would desynchronise
// `list.len() == index.len()` and leak a slot permanently).
self.index.reserve(1);
let evicted = if self.list.len() >= self.capacity {
let old_key = self.list.pop_back()?;
self.index.remove(&old_key);
Some(old_key)
} else {
None
};
let id = self.list.push_front(key.clone());
self.index.insert(key, id);
evicted
}
/// Records a batch of keys; returns number of keys processed.
///
/// Note: All keys are processed (count equals input length), since `record` is infallible.
/// Duplicates are automatically promoted to MRU rather than inserted twice.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost = GhostList::new(10);
///
/// let evicted = vec!["page_1", "page_2", "page_3"];
/// let count = ghost.record_batch(&evicted);
///
/// assert_eq!(count, 3);
/// assert_eq!(ghost.len(), 3);
/// ```
pub fn record_batch<'a, I>(&mut self, keys: I) -> usize
where
I: IntoIterator<Item = &'a K>,
K: 'a,
{
let mut count = 0;
for key in keys {
self.record(key.clone());
count += 1;
}
count
}
/// Removes `key` from the ghost list; returns `true` if it was present.
///
/// Typically called after a ghost hit to prevent double-counting.
///
/// # Complexity
///
/// O(1) average case, O(n) worst case due to hash collisions.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost = GhostList::new(10);
/// ghost.record("key");
///
/// // Ghost hit: remove from ghost list
/// assert!(ghost.remove(&"key"));
/// assert!(!ghost.contains(&"key"));
///
/// // Removing missing key returns false
/// assert!(!ghost.remove(&"missing"));
/// ```
pub fn remove(&mut self, key: &K) -> bool {
let id = match self.index.remove(key) {
Some(id) => id,
None => return false,
};
self.list.remove(id);
true
}
/// Removes and returns the LRU (least recently used) key.
///
/// Returns `None` if the ghost list is empty.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost = GhostList::new(3);
/// ghost.record("a");
/// ghost.record("b");
/// ghost.record("c");
///
/// // "a" is LRU (inserted first, never promoted)
/// assert_eq!(ghost.evict_lru(), Some("a"));
/// assert!(!ghost.contains(&"a"));
/// assert_eq!(ghost.len(), 2);
///
/// assert_eq!(ghost.evict_lru(), Some("b"));
/// assert_eq!(ghost.evict_lru(), Some("c"));
/// assert_eq!(ghost.evict_lru(), None); // Empty
/// ```
pub fn evict_lru(&mut self) -> Option<K> {
let key = self.list.pop_back()?;
self.index.remove(&key);
Some(key)
}
/// Removes a batch of keys; returns number of keys actually removed.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///
/// let mut ghost = GhostList::new(10);
/// ghost.record_batch(&["a", "b", "c"]);
///
/// // Remove some keys (including one that doesn't exist)
/// let removed = ghost.remove_batch(&["a", "c", "missing"]);
///
/// assert_eq!(removed, 2); // Only "a" and "c" were removed
/// assert!(ghost.contains(&"b"));
/// ```
pub fn remove_batch<'a, I>(&mut self, keys: I) -> usize
where
I: IntoIterator<Item = &'a K>,
K: 'a,
{
let mut removed = 0;
for key in keys {
if self.remove(key) {
removed += 1;
}
}
removed
}
/// Clears all tracked keys.
///
/// # Example
///
/// ```
/// use cachekit::ds::GhostList;
///