-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfrequency_buckets.rs
More file actions
3741 lines (3449 loc) · 115 KB
/
frequency_buckets.rs
File metadata and controls
3741 lines (3449 loc) · 115 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
//! Frequency buckets for O(1) LFU tracking.
//!
//! Provides LFU (Least Frequently Used) eviction metadata tracking with O(1)
//! insert, touch, remove, and eviction operations. Uses frequency buckets with
//! FIFO tie-breaking within each frequency level.
//!
//! ## Architecture
//!
//! ```text
//! ┌──────────────────────────────────────────────────────────────────────────┐
//! │ FrequencyBuckets<K> Layout │
//! │ │
//! │ ┌────────────────────────────┐ ┌─────────────────────────────────┐ │
//! │ │ index: HashMap<K, SlotId> │ │ entries: SlotArena<Entry<K>> │ │
//! │ │ │ │ │ │
//! │ │ ┌───────────┬──────────┐ │ │ ┌──────┬───────────────────┐ │ │
//! │ │ │ Key │ SlotId │ │ │ │ Slot │ Entry │ │ │
//! │ │ ├───────────┼──────────┤ │ │ ├──────┼───────────────────┤ │ │
//! │ │ │ "page_a" │ id_0 │──┼───┼──►│ id_0 │ freq:2, prev/next │ │ │
//! │ │ │ "page_b" │ id_1 │──┼───┼──►│ id_1 │ freq:1, prev/next │ │ │
//! │ │ │ "page_c" │ id_2 │──┼───┼──►│ id_2 │ freq:1, prev/next │ │ │
//! │ │ └───────────┴──────────┘ │ │ └──────┴───────────────────┘ │ │
//! │ └────────────────────────────┘ └─────────────────────────────────┘ │
//! │ │
//! │ ┌───────────────────────────────────────────────────────────────────┐ │
//! │ │ buckets: HashMap<u64, Bucket> (frequency → doubly-linked list) │ │
//! │ │ │ │
//! │ │ min_freq = 1 │ │
//! │ │ │ │ │
//! │ │ ▼ │ │
//! │ │ freq=1: head ──► [id_2] ◄──► [id_1] ◄── tail (FIFO order) │ │
//! │ │ MRU LRU (evict first) │ │
//! │ │ │ │
//! │ │ freq=2: head ──► [id_0] ◄── tail │ │
//! │ │ │ │
//! │ │ Bucket links: freq=1 ──next──► freq=2 │ │
//! │ │ freq=2 ◄──prev── freq=1 │ │
//! │ └───────────────────────────────────────────────────────────────────┘ │
//! │ │
//! └──────────────────────────────────────────────────────────────────────────┘
//!
//! Touch Flow (increment frequency)
//! ─────────────────────────────────
//!
//! touch("page_b"):
//! 1. Lookup id_1 in index
//! 2. Remove id_1 from freq=1 bucket list
//! 3. If freq=1 bucket empty → remove bucket, update min_freq
//! 4. Create freq=2 bucket if needed
//! 5. Push id_1 to front of freq=2 bucket (MRU)
//! 6. Update entry.freq = 2
//!
//! Eviction Flow (pop_min)
//! ───────────────────────
//!
//! pop_min():
//! 1. Use min_freq to find lowest bucket
//! 2. Pop tail of that bucket (oldest at that frequency)
//! 3. Remove entry from index and entries
//! 4. If bucket empty → remove bucket, update min_freq
//! 5. Return (key, freq)
//! ```
//!
//! ## Key Components
//!
//! - [`FrequencyBuckets`]: Single-threaded O(1) LFU tracker
//! - [`ShardedFrequencyBuckets`]: Concurrent sharded variant
//! - [`FrequencyBucketsHandle`]: Handle-based variant for interned keys
//! - [`Iter`]: Iterator over all entries; produced by [`FrequencyBuckets::iter`]
//! - [`BucketIds`]: Iterator over [`SlotId`]s in a bucket; produced by [`FrequencyBuckets::iter_bucket_ids`]
//! - [`BucketEntries`]: Iterator over `(SlotId, meta)` pairs in a bucket; produced by [`FrequencyBuckets::iter_bucket_entries`]
//!
//! ## Operations
//!
//! | Operation | Time | Notes |
//! |----------------|-------------|----------------------------------------|
//! | [`insert`](FrequencyBuckets::insert) | O(1) | New key starts at freq=1 |
//! | [`touch`](FrequencyBuckets::touch) | O(1) | Increment frequency, move to MRU |
//! | [`remove`](FrequencyBuckets::remove) | O(1) | Remove from tracking |
//! | [`pop_min`](FrequencyBuckets::pop_min) | O(1) | Evict LFU (FIFO tie-break) |
//! | [`frequency`](FrequencyBuckets::frequency) | O(1) | Query current frequency |
//! | [`decay_halve`](FrequencyBuckets::decay_halve) | O(n) | Halve all frequencies |
//! | [`rebase_min_freq`](FrequencyBuckets::rebase_min_freq) | O(n) | Rebase so min becomes 1 |
//! | [`iter`](FrequencyBuckets::iter) | O(n) | Iterate all entries |
//! | [`iter_bucket_ids`](FrequencyBuckets::iter_bucket_ids) | O(k) | Iterate bucket by frequency |
//!
//! ## Use Cases
//!
//! - **LFU cache policy**: Track access frequency for eviction
//! - **Hot/cold detection**: Identify frequently accessed items
//! - **Admission control**: Filter one-hit wonders
//!
//! ## Example Usage
//!
//! ```
//! use cachekit::ds::FrequencyBuckets;
//!
//! let mut freq = FrequencyBuckets::new();
//!
//! // Insert keys (all start at frequency 1)
//! freq.insert("page_a");
//! freq.insert("page_b");
//! freq.insert("page_c");
//!
//! // Access increases frequency
//! freq.touch(&"page_a"); // freq=2
//! freq.touch(&"page_a"); // freq=3
//!
//! // Evict LFU (lowest frequency, FIFO among ties)
//! let evicted = freq.pop_min();
//! assert_eq!(evicted, Some(("page_b", 1))); // First inserted at freq=1
//! ```
//!
//! ## Use Case: LFU Cache with Frequency Decay
//!
//! ```
//! use cachekit::ds::FrequencyBuckets;
//!
//! struct LfuCache {
//! freq: FrequencyBuckets<String>,
//! decay_interval: u64,
//! ops_since_decay: u64,
//! }
//!
//! impl LfuCache {
//! fn new(decay_interval: u64) -> Self {
//! Self {
//! freq: FrequencyBuckets::new(),
//! decay_interval,
//! ops_since_decay: 0,
//! }
//! }
//!
//! fn access(&mut self, key: &str) {
//! if !self.freq.contains(&key.to_string()) {
//! self.freq.insert(key.to_string());
//! } else {
//! self.freq.touch(&key.to_string());
//! }
//!
//! self.ops_since_decay += 1;
//! if self.ops_since_decay >= self.decay_interval {
//! self.freq.decay_halve(); // Prevent frequency inflation
//! self.ops_since_decay = 0;
//! }
//! }
//!
//! fn evict(&mut self) -> Option<String> {
//! self.freq.pop_min().map(|(k, _)| k)
//! }
//! }
//!
//! let mut cache = LfuCache::new(100);
//! cache.access("hot_page");
//! cache.access("hot_page");
//! cache.access("cold_page");
//!
//! assert_eq!(cache.freq.frequency(&"hot_page".to_string()), Some(2));
//! ```
//!
//! ## Handle-Based Usage
//!
//! For large keys, consider interning keys in a higher layer and using
//! [`FrequencyBucketsHandle<Handle>`] where `Handle: Copy + Eq + Hash`.
//! This stores the handle (not the full key) in buckets and index maps.
//!
//! ## Thread Safety
//!
//! - [`FrequencyBuckets`]: Not thread-safe
//! - [`ShardedFrequencyBuckets`]: Thread-safe via sharding with `RwLock`
//!
//! ## Implementation Notes
//!
//! - Buckets are doubly-linked for O(1) navigation
//! - FIFO within bucket: head=MRU, tail=LRU (evict from tail)
//! - `min_freq` pointer enables O(1) eviction
//! - `debug_validate_invariants()` available in debug/test builds
//!
use std::borrow::Borrow;
use std::hash::Hash;
use rustc_hash::FxHashMap;
use crate::ds::slot_arena::{SlotArena, SlotId};
/// LFU entry with cache-line optimized layout.
/// Link pointers (prev/next) are accessed on every touch/evict operation,
/// so they're placed first for better cache locality.
#[derive(Debug, Clone)]
#[repr(C)]
struct Entry<K> {
// Hot fields - accessed during list operations
prev: Option<SlotId>,
next: Option<SlotId>,
freq: u64,
last_epoch: u64,
// Cold field - only accessed on eviction
key: K,
}
#[derive(Debug, Default, Clone)]
struct Bucket {
head: Option<SlotId>,
tail: Option<SlotId>,
prev: Option<u64>,
next: Option<u64>,
}
/// O(1) LFU metadata tracker with FIFO tie-breaking within a frequency.
///
/// Tracks key frequencies for LFU eviction. Keys are organized into frequency
/// buckets, with FIFO ordering within each bucket for tie-breaking.
///
/// # Type Parameters
///
/// - `K`: Key type, must be `Eq + Hash + Clone`
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
///
/// // Insert and touch
/// freq.insert("a");
/// freq.insert("b");
/// freq.touch(&"a"); // "a" now at freq=2
///
/// // Query state
/// assert_eq!(freq.frequency(&"a"), Some(2));
/// assert_eq!(freq.frequency(&"b"), Some(1));
/// assert_eq!(freq.min_freq(), Some(1));
///
/// // Evict LFU
/// let (key, freq_val) = freq.pop_min().unwrap();
/// assert_eq!(key, "b");
/// assert_eq!(freq_val, 1);
/// ```
///
/// # Use Case: Admission Filter
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// // Only admit keys that have been seen multiple times
/// let mut freq: FrequencyBuckets<String> = FrequencyBuckets::new();
///
/// fn should_admit(freq: &mut FrequencyBuckets<String>, key: &str) -> bool {
/// let key_str = key.to_string();
/// if freq.contains(&key_str) {
/// let new_freq = freq.touch(&key_str).unwrap();
/// new_freq >= 2 // Admit after 2nd access
/// } else {
/// freq.insert(key_str);
/// false // Don't admit on first access
/// }
/// }
///
/// assert!(!should_admit(&mut freq, "page_x")); // First access
/// assert!(should_admit(&mut freq, "page_x")); // Second access - admit!
/// ```
#[derive(Debug, Clone)]
pub struct FrequencyBuckets<K> {
entries: SlotArena<Entry<K>>,
index: FxHashMap<K, SlotId>,
buckets: FxHashMap<u64, Bucket>,
min_freq: u64,
epoch: u64,
}
/// Read-only view of a frequency bucket entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct FrequencyBucketEntryMeta<'a, K> {
pub key: &'a K,
pub freq: u64,
pub last_epoch: u64,
}
/// Owned view of a frequency bucket entry for sharded readers.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ShardedFrequencyBucketEntryMeta<K> {
pub key: K,
pub freq: u64,
pub last_epoch: u64,
}
/// Debug view of a bucket entry for snapshots.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct FrequencyBucketEntryDebug<K> {
pub id: SlotId,
pub key: K,
pub freq: u64,
pub last_epoch: u64,
}
/// Default bucket pre-allocation for typical frequency distributions.
/// Most items cluster at low frequencies (1-32), so 32 buckets covers most cases.
pub const DEFAULT_BUCKET_PREALLOC: usize = 32;
impl<K> FrequencyBuckets<K>
where
K: Eq + Hash + Clone,
{
/// Creates an empty tracker with reserved capacity for entries and index.
///
/// Uses [`DEFAULT_BUCKET_PREALLOC`] for the bucket map. For custom bucket
/// pre-allocation, use [`with_capacity_and_bucket_hint`](Self::with_capacity_and_bucket_hint).
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let freq: FrequencyBuckets<String> = FrequencyBuckets::with_capacity(1000);
/// assert!(freq.is_empty());
/// ```
pub fn with_capacity(capacity: usize) -> Self {
Self::with_capacity_and_bucket_hint(capacity, DEFAULT_BUCKET_PREALLOC)
}
/// Creates an empty tracker with reserved capacity and custom bucket pre-allocation.
///
/// # Arguments
///
/// * `capacity` - Pre-allocated space for entries and index
/// * `bucket_hint` - Pre-allocated space for frequency buckets (number of distinct frequencies)
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// // Expect many distinct frequencies (e.g., long-running cache with varied access patterns)
/// let freq: FrequencyBuckets<String> = FrequencyBuckets::with_capacity_and_bucket_hint(1000, 64);
/// assert!(freq.is_empty());
/// ```
pub fn with_capacity_and_bucket_hint(capacity: usize, bucket_hint: usize) -> Self {
Self {
entries: SlotArena::with_capacity(capacity),
index: FxHashMap::with_capacity_and_hasher(capacity, Default::default()),
buckets: FxHashMap::with_capacity_and_hasher(bucket_hint, Default::default()),
min_freq: 0,
epoch: 0,
}
}
/// Creates an empty tracker.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let freq: FrequencyBuckets<&str> = FrequencyBuckets::new();
/// assert!(freq.is_empty());
/// ```
pub fn new() -> Self {
Self {
entries: SlotArena::new(),
index: FxHashMap::default(),
buckets: FxHashMap::default(),
min_freq: 0,
epoch: 0,
}
}
/// Returns the number of tracked keys.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// assert_eq!(freq.len(), 0);
///
/// freq.insert("a");
/// freq.insert("b");
/// assert_eq!(freq.len(), 2);
/// ```
pub fn len(&self) -> usize {
self.entries.len()
}
/// Returns `true` if there are no tracked keys.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq: FrequencyBuckets<&str> = FrequencyBuckets::new();
/// assert!(freq.is_empty());
///
/// freq.insert("key");
/// assert!(!freq.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// Returns `true` if `key` is present.
///
/// Accepts borrowed forms of the key type via [`Borrow`].
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert("hello".to_string());
///
/// assert!(freq.contains("hello")); // Query with &str
/// assert!(!freq.contains("missing"));
/// ```
#[inline]
pub fn contains<Q>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.index.contains_key(key)
}
/// Returns the current epoch.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let freq: FrequencyBuckets<&str> = FrequencyBuckets::new();
/// assert_eq!(freq.current_epoch(), 0);
/// ```
pub fn current_epoch(&self) -> u64 {
self.epoch
}
/// Advances the epoch counter and returns the new value.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq: FrequencyBuckets<&str> = FrequencyBuckets::new();
/// assert_eq!(freq.advance_epoch(), 1);
/// assert_eq!(freq.advance_epoch(), 2);
/// assert_eq!(freq.current_epoch(), 2);
/// ```
pub fn advance_epoch(&mut self) -> u64 {
self.epoch = self.epoch.wrapping_add(1);
self.epoch
}
/// Sets the epoch counter.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq: FrequencyBuckets<&str> = FrequencyBuckets::new();
/// freq.set_epoch(100);
/// assert_eq!(freq.current_epoch(), 100);
/// ```
pub fn set_epoch(&mut self, epoch: u64) {
self.epoch = epoch;
}
/// Returns the current frequency for `key`, if present.
///
/// Accepts borrowed forms of the key type via [`Borrow`].
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert("hello".to_string());
/// freq.touch("hello");
///
/// assert_eq!(freq.frequency("hello"), Some(2));
/// assert_eq!(freq.frequency("missing"), None);
/// ```
#[inline]
pub fn frequency<Q>(&self, key: &Q) -> Option<u64>
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
let id = *self.index.get(key)?;
self.entries.get(id).map(|entry| entry.freq)
}
/// Returns the last epoch recorded for `key`.
///
/// Accepts borrowed forms of the key type via [`Borrow`].
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.set_epoch(10);
/// freq.insert("key");
///
/// assert_eq!(freq.entry_epoch(&"key"), Some(10));
/// assert_eq!(freq.entry_epoch(&"missing"), None);
/// ```
pub fn entry_epoch<Q>(&self, key: &Q) -> Option<u64>
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
let id = *self.index.get(key)?;
self.entries.get(id).map(|entry| entry.last_epoch)
}
/// Sets the last epoch for `key`; returns `false` if missing.
///
/// Accepts borrowed forms of the key type via [`Borrow`].
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert("key");
///
/// assert!(freq.set_entry_epoch(&"key", 42));
/// assert_eq!(freq.entry_epoch(&"key"), Some(42));
///
/// assert!(!freq.set_entry_epoch(&"missing", 42));
/// ```
pub fn set_entry_epoch<Q>(&mut self, key: &Q, epoch: u64) -> bool
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
let id = match self.index.get(key) {
Some(id) => *id,
None => return false,
};
if let Some(entry) = self.entries.get_mut(id) {
entry.last_epoch = epoch;
return true;
}
false
}
/// Returns the minimum frequency currently present.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// assert_eq!(freq.min_freq(), None);
///
/// freq.insert("a");
/// freq.insert("b");
/// freq.touch(&"a"); // "a" at freq=2, "b" at freq=1
///
/// assert_eq!(freq.min_freq(), Some(1));
/// ```
pub fn min_freq(&self) -> Option<u64> {
if self.min_freq == 0 {
None
} else {
Some(self.min_freq)
}
}
/// Peeks the eviction candidate `(key, freq)` (tail of the min-frequency bucket).
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert("a");
/// freq.insert("b");
/// freq.touch(&"b"); // "b" at freq=2
///
/// // "a" is the eviction candidate (freq=1, oldest)
/// let (key, freq_val) = freq.peek_min().unwrap();
/// assert_eq!(*key, "a");
/// assert_eq!(freq_val, 1);
/// assert_eq!(freq.len(), 2); // Not removed
/// ```
pub fn peek_min(&self) -> Option<(&K, u64)> {
if self.min_freq == 0 {
return None;
}
let min_freq = self.min_freq;
let bucket = self.buckets.get(&min_freq)?;
let id = bucket.tail?;
let entry = self.entries.get(id)?;
Some((&entry.key, entry.freq))
}
/// Peeks the SlotId for the eviction candidate (tail of the min-frequency bucket).
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// assert!(freq.peek_min_id().is_none());
///
/// freq.insert("a");
/// freq.insert("b");
///
/// let id = freq.peek_min_id().unwrap();
/// // The SlotId can be used to look up entry metadata
/// ```
pub fn peek_min_id(&self) -> Option<SlotId> {
if self.min_freq == 0 {
return None;
}
let bucket = self.buckets.get(&self.min_freq)?;
bucket.tail
}
/// Peeks the key for the eviction candidate (tail of the min-frequency bucket).
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert("a");
/// freq.insert("b");
/// freq.touch(&"b");
///
/// // "a" is the eviction candidate (lowest freq, oldest)
/// assert_eq!(freq.peek_min_key(), Some(&"a"));
/// ```
pub fn peek_min_key(&self) -> Option<&K> {
let id = self.peek_min_id()?;
self.entries.get(id).map(|entry| &entry.key)
}
/// Returns an iterator of SlotIds for a given frequency, from head to tail.
///
/// Head is the most recently touched entry at that frequency (MRU),
/// tail is the oldest (LRU, evict first).
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert("a");
/// freq.insert("b");
/// freq.insert("c");
///
/// let ids: Vec<_> = freq.iter_bucket_ids(1).collect();
/// assert_eq!(ids.len(), 3);
/// ```
pub fn iter_bucket_ids(&self, freq: u64) -> BucketIds<'_, K> {
let head = self.buckets.get(&freq).and_then(|bucket| bucket.head);
BucketIds {
buckets: self,
current: head,
}
}
/// Returns an iterator of `(SlotId, meta)` for a given frequency.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert("a");
/// freq.insert("b");
/// freq.touch(&"a"); // "a" moves to freq=2
///
/// // Only "b" is at frequency 1
/// let entries: Vec<_> = freq.iter_bucket_entries(1).collect();
/// assert_eq!(entries.len(), 1);
/// assert_eq!(*entries[0].1.key, "b");
/// ```
pub fn iter_bucket_entries(&self, freq: u64) -> BucketEntries<'_, K> {
let head = self.buckets.get(&freq).and_then(|bucket| bucket.head);
BucketEntries {
buckets: self,
current: head,
}
}
/// Returns an iterator over all `(SlotId, meta)` entries.
///
/// Yields every tracked entry in unspecified (arena) order.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert("a");
/// freq.insert("b");
/// freq.touch(&"a");
///
/// let entries: Vec<_> = freq.iter().collect();
/// assert_eq!(entries.len(), 2);
///
/// // Check we have both keys
/// let keys: Vec<_> = entries.iter().map(|(_, m)| *m.key).collect();
/// assert!(keys.contains(&"a"));
/// assert!(keys.contains(&"b"));
/// ```
pub fn iter(&self) -> Iter<'_, K> {
Iter {
inner: self.entries.iter(),
}
}
/// Inserts a new key with frequency 1.
///
/// Returns `false` if the key already exists (no update performed).
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
///
/// assert!(freq.insert("a")); // New key
/// assert!(!freq.insert("a")); // Already exists
/// assert_eq!(freq.frequency(&"a"), Some(1));
/// ```
#[inline]
pub fn insert(&mut self, key: K) -> bool {
if self.index.contains_key(&key) {
return false;
}
let id = self.entries.insert(Entry {
key: key.clone(),
freq: 1,
last_epoch: self.epoch,
prev: None,
next: None,
});
self.index.insert(key, id);
if !self.buckets.contains_key(&1) {
let next = if self.min_freq == 0 {
None
} else {
Some(self.min_freq)
};
self.insert_bucket(1, None, next);
}
self.list_push_front(1, id);
if self.min_freq == 0 || self.min_freq > 1 {
self.min_freq = 1;
}
true
}
/// Inserts a batch of keys; returns number of newly inserted keys.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// let inserted = freq.insert_batch(["a", "b", "c", "a"]); // "a" duplicated
///
/// assert_eq!(inserted, 3); // Only 3 unique keys inserted
/// assert_eq!(freq.len(), 3);
/// ```
pub fn insert_batch<I>(&mut self, keys: I) -> usize
where
I: IntoIterator<Item = K>,
{
let mut inserted = 0;
for key in keys {
if self.insert(key) {
inserted += 1;
}
}
inserted
}
/// Increments frequency for `key` and returns the new frequency.
///
/// Returns `None` if `key` is missing. Within each frequency bucket,
/// the key is treated as MRU by being pushed to the front.
///
/// Accepts borrowed forms of the key type via [`Borrow`].
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert("key");
///
/// assert_eq!(freq.touch(&"key"), Some(2));
/// assert_eq!(freq.touch(&"key"), Some(3));
/// assert_eq!(freq.touch(&"missing"), None);
/// ```
#[inline]
pub fn touch<Q>(&mut self, key: &Q) -> Option<u64>
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
let id = *self.index.get(key)?;
let current_freq = self.entries.get(id)?.freq;
if current_freq == u64::MAX {
self.list_remove(current_freq, id)?;
self.list_push_front(current_freq, id);
if let Some(entry) = self.entries.get_mut(id) {
entry.last_epoch = self.epoch;
}
return Some(current_freq);
}
let next_freq = current_freq + 1;
let (prev_freq, next_existing) = {
let bucket = self.buckets.get(¤t_freq)?;
(bucket.prev, bucket.next)
};
self.list_remove(current_freq, id)?;
let bucket_empty = self.bucket_is_empty(current_freq);
if bucket_empty {
self.remove_bucket(current_freq, prev_freq, next_existing);
if self.min_freq == current_freq {
self.min_freq = next_existing.unwrap_or(0);
}
}
if !self.buckets.contains_key(&next_freq) {
let prev = if bucket_empty {
prev_freq
} else {
Some(current_freq)
};
let next = next_existing;
self.insert_bucket(next_freq, prev, next);
}
if let Some(entry) = self.entries.get_mut(id) {
entry.freq = next_freq;
entry.last_epoch = self.epoch;
}
self.list_push_front(next_freq, id);
if self.min_freq == 0 || next_freq < self.min_freq {
self.min_freq = next_freq;
}
Some(next_freq)
}
/// Touches a batch of keys; returns number of keys found.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert_batch(["a", "b", "c"]);
///
/// let touched = freq.touch_batch(["a", "b", "missing"]);
/// assert_eq!(touched, 2); // Only "a" and "b" found
/// ```
pub fn touch_batch<I>(&mut self, keys: I) -> usize
where
I: IntoIterator<Item = K>,
{
let mut touched = 0;
for key in keys {
if self.touch(&key).is_some() {
touched += 1;
}
}
touched
}
/// Increments frequency for `key`, clamping at `max_freq`.
///
/// If the key is already at `max_freq`, it is moved to the front of its
/// bucket (MRU position) and the frequency is unchanged.
///
/// Accepts borrowed forms of the key type via [`Borrow`].
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert("key");
///
/// assert_eq!(freq.touch_capped(&"key", 3), Some(2));
/// assert_eq!(freq.touch_capped(&"key", 3), Some(3));
/// assert_eq!(freq.touch_capped(&"key", 3), Some(3)); // Capped
/// assert_eq!(freq.frequency(&"key"), Some(3));
/// ```
pub fn touch_capped<Q>(&mut self, key: &Q, max_freq: u64) -> Option<u64>
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
let max_freq = max_freq.max(1);
let id = *self.index.get(key)?;
let current_freq = self.entries.get(id)?.freq;
if current_freq >= max_freq {
self.list_remove(current_freq, id)?;
self.list_push_front(current_freq, id);
if let Some(entry) = self.entries.get_mut(id) {
entry.last_epoch = self.epoch;
}
return Some(current_freq);
}
let next_freq = current_freq + 1;
let (prev_freq, next_existing) = {
let bucket = self.buckets.get(¤t_freq)?;
(bucket.prev, bucket.next)
};
self.list_remove(current_freq, id)?;
let bucket_empty = self.bucket_is_empty(current_freq);
if bucket_empty {
self.remove_bucket(current_freq, prev_freq, next_existing);
if self.min_freq == current_freq {
self.min_freq = next_existing.unwrap_or(0);
}
}
if !self.buckets.contains_key(&next_freq) {
let prev = if bucket_empty {
prev_freq
} else {
Some(current_freq)
};
let next = next_existing;
self.insert_bucket(next_freq, prev, next);
}
if let Some(entry) = self.entries.get_mut(id) {
entry.freq = next_freq;
entry.last_epoch = self.epoch;
}
self.list_push_front(next_freq, id);
if self.min_freq == 0 || next_freq < self.min_freq {
self.min_freq = next_freq;
}
Some(next_freq)
}
/// Halves all frequencies (rounding down), clamping at 1.
///
/// This is an O(n) rebuild and will reorder tie-breaks within buckets.
/// Useful for preventing frequency inflation over time.
///
/// # Example
///
/// ```
/// use cachekit::ds::FrequencyBuckets;
///
/// let mut freq = FrequencyBuckets::new();
/// freq.insert("a");
/// freq.insert("b");
///
/// // Build up frequencies
/// for _ in 0..9 { freq.touch(&"a"); } // "a" at freq=10
/// for _ in 0..3 { freq.touch(&"b"); } // "b" at freq=4