token_bucket/keyed/impl.rs
1use super::*;
2
3/// Policy dispatch helpers for `RateLimitPolicy`.
4impl RateLimitPolicy {
5 /// Returns the configured burst or per-window limit of this policy.
6 ///
7 /// # Returns
8 ///
9 /// - `u64` - Configured burst or window limit.
10 #[inline(always)]
11 pub fn limit(&self) -> u64 {
12 match self {
13 Self::Gcra(cfg) => cfg.get_burst(),
14 Self::FixedWindow(cfg) => cfg.get_limit(),
15 Self::TokenBucket(cfg) => cfg.get_capacity(),
16 }
17 }
18
19 /// Returns the initial raw `u64` atomic word for a brand-new key at `now_ns`.
20 ///
21 /// # Arguments
22 ///
23 /// - `u64` - Current monotonic timestamp in nanoseconds.
24 ///
25 /// # Returns
26 ///
27 /// - `u64` - Initial packed atomic state word.
28 #[inline(always)]
29 pub(crate) fn initial_state_at_ns(&self, now_ns: u64) -> u64 {
30 match self {
31 Self::Gcra(_) => 0,
32 Self::FixedWindow(_) => 0,
33 Self::TokenBucket(cfg) => {
34 let step_low: u64 = cfg.div_step_ns(now_ns) & cfg.get_step_mask();
35 (step_low << cfg.get_token_bits()) | cfg.get_capacity()
36 }
37 }
38 }
39
40 /// Checks whether a key entry's atomic state is currently idle at `now_ns`.
41 ///
42 /// # Arguments
43 ///
44 /// - `&AtomicU64` - Per-key atomic state storage.
45 /// - `u64` - Current monotonic timestamp in nanoseconds.
46 ///
47 /// # Returns
48 ///
49 /// - `bool` - `true` when the key has zero active debt or usage.
50 #[inline(always)]
51 pub(crate) fn is_idle_atomic(&self, atomic: &AtomicU64, now_ns: u64) -> bool {
52 match self {
53 Self::Gcra(_) => GcraCell::is_idle_atomic(atomic, now_ns),
54 Self::FixedWindow(cfg) => FixedWindowCell::is_idle_atomic(atomic, cfg, now_ns),
55 Self::TokenBucket(cfg) => TokenBucketCell::is_idle_atomic(atomic, cfg, now_ns),
56 }
57 }
58
59 /// Performs a non-mutating availability probe on an existing key's atomic state.
60 ///
61 /// # Arguments
62 ///
63 /// - `&AtomicU64` - Per-key atomic state storage.
64 /// - `u64` - Current monotonic timestamp in nanoseconds.
65 ///
66 /// # Returns
67 ///
68 /// - `RateLimitDecision` - Availability snapshot.
69 #[inline(always)]
70 pub(crate) fn peek_atomic(&self, atomic: &AtomicU64, now_ns: u64) -> RateLimitDecision {
71 match self {
72 Self::Gcra(cfg) => GcraCell::peek_atomic(atomic, cfg, now_ns),
73 Self::FixedWindow(cfg) => FixedWindowCell::peek_atomic(atomic, cfg, now_ns),
74 Self::TokenBucket(cfg) => TokenBucketCell::peek_atomic(atomic, cfg, now_ns),
75 }
76 }
77
78 /// Returns a fresh availability snapshot for an unseen key at `now_ns`.
79 ///
80 /// # Arguments
81 ///
82 /// - `u64` - Current monotonic timestamp in nanoseconds.
83 ///
84 /// # Returns
85 ///
86 /// - `RateLimitDecision` - Full-quota decision snapshot.
87 #[inline(always)]
88 pub(crate) fn peek_absent_at_ns(&self, now_ns: u64) -> RateLimitDecision {
89 match self {
90 Self::Gcra(cfg) => RateLimitDecision::new(true, cfg.get_burst(), 0, 0, cfg.get_burst()),
91 Self::FixedWindow(cfg) => {
92 let reset_ns: u64 = FixedWindowCell::current_window_remaining_ns(cfg, now_ns);
93 RateLimitDecision::new(true, cfg.get_limit(), reset_ns, 0, cfg.get_limit())
94 }
95 Self::TokenBucket(cfg) => {
96 RateLimitDecision::new(true, cfg.get_capacity(), 0, 0, cfg.get_capacity())
97 }
98 }
99 }
100
101 /// Executes the lock-free atomic check-and-consume transition for `cost` units.
102 ///
103 /// # Arguments
104 ///
105 /// - `&AtomicU64` - Per-key atomic state storage.
106 /// - `u64` - Current monotonic timestamp in nanoseconds.
107 /// - `u64` - Number of quota units to consume.
108 ///
109 /// # Returns
110 ///
111 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
112 #[inline(always)]
113 pub(crate) fn check_n_atomic(
114 &self,
115 atomic: &AtomicU64,
116 now_ns: u64,
117 cost: u64,
118 ) -> RateLimitDecision {
119 match self {
120 Self::Gcra(cfg) => GcraCell::check_n_atomic(atomic, cfg, now_ns, cost),
121 Self::FixedWindow(cfg) => FixedWindowCell::check_n_atomic(atomic, cfg, now_ns, cost),
122 Self::TokenBucket(cfg) => TokenBucketCell::check_n_atomic(atomic, cfg, now_ns, cost),
123 }
124 }
125}
126
127/// Converts a `GcraConfig` into `RateLimitPolicy::Gcra`.
128impl From<GcraConfig> for RateLimitPolicy {
129 /// Wraps a `GcraConfig` into `RateLimitPolicy`.
130 ///
131 /// # Arguments
132 ///
133 /// - `GcraConfig` - GCRA configuration.
134 #[inline(always)]
135 fn from(config: GcraConfig) -> Self {
136 Self::Gcra(config)
137 }
138}
139
140/// Converts a `FixedWindowConfig` into `RateLimitPolicy::FixedWindow`.
141impl From<FixedWindowConfig> for RateLimitPolicy {
142 /// Wraps a `FixedWindowConfig` into `RateLimitPolicy`.
143 ///
144 /// # Arguments
145 ///
146 /// - `FixedWindowConfig` - Fixed-window configuration.
147 #[inline(always)]
148 fn from(config: FixedWindowConfig) -> Self {
149 Self::FixedWindow(config)
150 }
151}
152
153/// Converts a `TokenBucketConfig` into `RateLimitPolicy::TokenBucket`.
154impl From<TokenBucketConfig> for RateLimitPolicy {
155 /// Wraps a `TokenBucketConfig` into `RateLimitPolicy`.
156 ///
157 /// # Arguments
158 ///
159 /// - `TokenBucketConfig` - Token-bucket configuration.
160 #[inline(always)]
161 fn from(config: TokenBucketConfig) -> Self {
162 Self::TokenBucket(config)
163 }
164}
165
166/// Accessors and timestamp helpers for `KeyEntry`.
167impl KeyEntry {
168 /// Creates a new `KeyEntry` initialized with raw atomic `state` and `now_ns`.
169 ///
170 /// # Arguments
171 ///
172 /// - `u64` - Initial algorithm-specific atomic state word.
173 /// - `u64` - Initial access timestamp in nanoseconds.
174 #[inline(always)]
175 pub(crate) fn new(state: u64, now_ns: u64) -> Self {
176 Self {
177 state: AtomicU64::new(state),
178 last_seen_ns: AtomicU64::new(now_ns),
179 }
180 }
181
182 /// Returns a reference to the algorithm-specific atomic state word.
183 ///
184 /// # Returns
185 ///
186 /// - `&AtomicU64` - Reference to the atomic state word.
187 #[inline(always)]
188 pub(crate) fn get_state(&self) -> &AtomicU64 {
189 &self.state
190 }
191
192 /// Returns a reference to the atomic last-seen timestamp.
193 ///
194 /// # Returns
195 ///
196 /// - `&AtomicU64` - Reference to the last-seen atomic timestamp.
197 #[inline(always)]
198 pub(crate) fn get_last_seen_ns(&self) -> &AtomicU64 {
199 &self.last_seen_ns
200 }
201
202 /// Records the latest access timestamp without memory-ordering fence overhead.
203 ///
204 /// # Arguments
205 ///
206 /// - `u64` - Current monotonic timestamp in nanoseconds.
207 #[inline(always)]
208 pub(crate) fn touch(&self, now_ns: u64) {
209 self.get_last_seen_ns().store(now_ns, Ordering::Relaxed);
210 }
211
212 /// Loads the recorded last-seen timestamp in nanoseconds.
213 ///
214 /// # Returns
215 ///
216 /// - `u64` - Last-seen monotonic timestamp in nanoseconds.
217 #[inline(always)]
218 pub(crate) fn load_last_seen_ns(&self) -> u64 {
219 self.get_last_seen_ns().load(Ordering::Relaxed)
220 }
221}
222
223/// Accessors for `ShardSlot`.
224impl<K> ShardSlot<K> {
225 /// Creates a new occupied shard slot.
226 ///
227 /// # Arguments
228 ///
229 /// - `u64` - Precomputed 64-bit hash of `key`.
230 /// - `K` - Owned key value.
231 /// - `KeyEntry` - Per-key atomic rate-limit state.
232 ///
233 /// # Returns
234 ///
235 /// - `Self` - Constructed slot record.
236 #[inline(always)]
237 pub(crate) fn new(hash: u64, key: K, entry: KeyEntry) -> Self {
238 Self { hash, key, entry }
239 }
240
241 /// Returns the precomputed 64-bit hash of the stored key.
242 ///
243 /// # Returns
244 ///
245 /// - `u64` - Stored key hash.
246 #[inline(always)]
247 pub(crate) fn get_hash(&self) -> u64 {
248 self.hash
249 }
250
251 /// Returns a reference to the stored key.
252 ///
253 /// # Returns
254 ///
255 /// - `&K` - Key reference.
256 #[inline(always)]
257 pub(crate) fn get_key(&self) -> &K {
258 &self.key
259 }
260
261 /// Returns a reference to the stored atomic rate-limit entry.
262 ///
263 /// # Returns
264 ///
265 /// - `&KeyEntry` - Entry reference.
266 #[inline(always)]
267 pub(crate) fn get_entry(&self) -> &KeyEntry {
268 &self.entry
269 }
270}
271
272/// Single-hash open-addressing map operations for `ShardMap`.
273impl<K> ShardMap<K> {
274 /// Creates an empty `ShardMap` with zero heap allocation.
275 ///
276 /// # Returns
277 ///
278 /// - `Self` - Empty map instance.
279 #[inline(always)]
280 pub(crate) const fn new() -> Self {
281 Self {
282 ctrl: Vec::new(),
283 slots: Vec::new(),
284 len: 0,
285 tombstones: 0,
286 }
287 }
288
289 /// Computes the 1-byte occupied H2 fingerprint tag from a 64-bit hash.
290 ///
291 /// # Arguments
292 ///
293 /// - `u64` - 64-bit key hash.
294 ///
295 /// # Returns
296 ///
297 /// - `u8` - Control byte with `SLOT_OCCUPIED_BIT` set.
298 #[inline(always)]
299 fn h2_tag(hash: u64) -> u8 {
300 SLOT_OCCUPIED_BIT | ((hash >> SLOT_H2_SHIFT) as u8)
301 }
302
303 /// Returns the control metadata slice.
304 ///
305 /// # Returns
306 ///
307 /// - `&[u8]` - Control tag slice.
308 #[inline(always)]
309 fn get_ctrl(&self) -> &[u8] {
310 &self.ctrl
311 }
312
313 /// Returns mutable access to the control metadata vector.
314 ///
315 /// # Returns
316 ///
317 /// - `&mut Vec<u8>` - Mutable control vector.
318 #[inline(always)]
319 fn get_mut_ctrl(&mut self) -> &mut Vec<u8> {
320 &mut self.ctrl
321 }
322
323 /// Returns the slot storage slice.
324 ///
325 /// # Returns
326 ///
327 /// - `&[Option<ShardSlot<K>>]` - Slot slice.
328 #[inline(always)]
329 fn get_slots(&self) -> &[Option<ShardSlot<K>>] {
330 &self.slots
331 }
332
333 /// Returns mutable access to the slot storage vector.
334 ///
335 /// # Returns
336 ///
337 /// - `&mut Vec<Option<ShardSlot<K>>>` - Mutable slot vector.
338 #[inline(always)]
339 fn get_mut_slots(&mut self) -> &mut Vec<Option<ShardSlot<K>>> {
340 &mut self.slots
341 }
342
343 /// Returns the live entry count field.
344 ///
345 /// # Returns
346 ///
347 /// - `usize` - Live entry count.
348 #[inline(always)]
349 fn get_len(&self) -> usize {
350 self.len
351 }
352
353 /// Returns the number of live entries stored in this shard map.
354 ///
355 /// # Returns
356 ///
357 /// - `usize` - Live entry count.
358 #[inline(always)]
359 pub(crate) fn len(&self) -> usize {
360 self.get_len()
361 }
362
363 /// Sets the live entry count.
364 ///
365 /// # Arguments
366 ///
367 /// - `usize` - New live entry count.
368 #[inline(always)]
369 fn set_len(&mut self, len: usize) {
370 self.len = len;
371 }
372
373 /// Returns the number of tombstones stored in `ctrl`.
374 ///
375 /// # Returns
376 ///
377 /// - `usize` - Tombstone count.
378 #[inline(always)]
379 fn get_tombstones(&self) -> usize {
380 self.tombstones
381 }
382
383 /// Sets the tombstone count.
384 ///
385 /// # Arguments
386 ///
387 /// - `usize` - New tombstone count.
388 #[inline(always)]
389 fn set_tombstones(&mut self, tombstones: usize) {
390 self.tombstones = tombstones;
391 }
392
393 /// Returns whether the shard map contains zero live entries.
394 ///
395 /// # Returns
396 ///
397 /// - `bool` - `true` when empty.
398 #[inline(always)]
399 pub(crate) fn is_empty(&self) -> bool {
400 self.len() == 0
401 }
402
403 /// Looks up `key` using its precomputed 64-bit `hash` without re-hashing.
404 ///
405 /// # Arguments
406 ///
407 /// - `u64` - Precomputed 64-bit hash of `key`.
408 /// - `&Q` - Borrowed key reference.
409 ///
410 /// # Returns
411 ///
412 /// - `Option<&KeyEntry>` - Matching entry reference if present.
413 #[inline(always)]
414 pub(crate) fn get_by_hash<Q>(&self, hash: u64, key: &Q) -> Option<&KeyEntry>
415 where
416 K: Borrow<Q>,
417 Q: Eq + ?Sized,
418 {
419 let ctrl: &[u8] = self.get_ctrl();
420 let cap: usize = ctrl.len();
421 if cap == 0 {
422 return None;
423 }
424 let mask: usize = cap - 1;
425 let h2: u8 = Self::h2_tag(hash);
426 let slots: &[Option<ShardSlot<K>>] = self.get_slots();
427 let mut idx: usize = (hash as usize) & mask;
428 loop {
429 let tag: u8 = unsafe { *ctrl.get_unchecked(idx) };
430 if tag == h2 {
431 let slot: &ShardSlot<K> =
432 unsafe { slots.get_unchecked(idx).as_ref().unwrap_unchecked() };
433 if slot.get_hash() == hash && slot.get_key().borrow() == key {
434 return Some(slot.get_entry());
435 }
436 } else if tag == SLOT_EMPTY {
437 return None;
438 }
439 idx = (idx + 1) & mask;
440 }
441 }
442
443 /// Rebuilds the open-addressing table at power-of-two capacity `new_cap`.
444 ///
445 /// # Arguments
446 ///
447 /// - `usize` - New power-of-two slot capacity (`>= SHARD_MAP_MIN_CAP`).
448 fn rehash(&mut self, new_cap: usize) {
449 let mut new_ctrl: Vec<u8> = vec![SLOT_EMPTY; new_cap];
450 let mut new_slots: Vec<Option<ShardSlot<K>>> = Vec::with_capacity(new_cap);
451 let mut init_idx: usize = 0;
452 while init_idx < new_cap {
453 new_slots.push(None);
454 init_idx += 1;
455 }
456 let mask: usize = new_cap - 1;
457 let old_slots: Vec<Option<ShardSlot<K>>> = mem::replace(self.get_mut_slots(), new_slots);
458 for slot in old_slots.into_iter().flatten() {
459 let hash: u64 = slot.get_hash();
460 let h2: u8 = Self::h2_tag(hash);
461 let mut idx: usize = (hash as usize) & mask;
462 while new_ctrl[idx] != SLOT_EMPTY {
463 idx = (idx + 1) & mask;
464 }
465 new_ctrl[idx] = h2;
466 self.get_mut_slots()[idx] = Some(slot);
467 }
468 *self.get_mut_ctrl() = new_ctrl;
469 self.set_tombstones(0);
470 }
471
472 /// Inserts `(hash, key, entry)`, growing or compacting the table when load exceeds 7/8.
473 ///
474 /// # Arguments
475 ///
476 /// - `u64` - Precomputed 64-bit hash of `key`.
477 /// - `K` - Owned key value.
478 /// - `KeyEntry` - Per-key atomic rate-limit state.
479 pub(crate) fn insert_with_hash(&mut self, hash: u64, key: K, entry: KeyEntry)
480 where
481 K: Eq,
482 {
483 let mut cap: usize = self.get_ctrl().len();
484 if cap == 0 {
485 self.rehash(SHARD_MAP_MIN_CAP);
486 cap = SHARD_MAP_MIN_CAP;
487 } else if (self.len() + self.get_tombstones() + 1) * 8 >= cap * 7 {
488 let next_cap: usize = if (self.len() + 1) * 2 <= cap {
489 cap
490 } else {
491 cap * 2
492 };
493 self.rehash(next_cap);
494 cap = next_cap;
495 }
496 let mask: usize = cap - 1;
497 let h2: u8 = Self::h2_tag(hash);
498 let mut idx: usize = (hash as usize) & mask;
499 let mut first_tombstone: Option<usize> = None;
500 loop {
501 let tag: u8 = self.get_ctrl()[idx];
502 if tag == h2 {
503 if let Some(slot) = &self.get_slots()[idx]
504 && slot.get_hash() == hash
505 && *slot.get_key() == key
506 {
507 self.get_mut_slots()[idx] = Some(ShardSlot::new(hash, key, entry));
508 return;
509 }
510 } else if tag == SLOT_EMPTY {
511 let target: usize = match first_tombstone {
512 Some(tomb_idx) => {
513 let next_tombs: usize = self.get_tombstones() - 1;
514 self.set_tombstones(next_tombs);
515 tomb_idx
516 }
517 None => idx,
518 };
519 self.get_mut_ctrl()[target] = h2;
520 self.get_mut_slots()[target] = Some(ShardSlot::new(hash, key, entry));
521 let next_len: usize = self.len() + 1;
522 self.set_len(next_len);
523 return;
524 } else if tag == SLOT_TOMBSTONE && first_tombstone.is_none() {
525 first_tombstone = Some(idx);
526 }
527 idx = (idx + 1) & mask;
528 }
529 }
530
531 /// Removes `key` by precomputed 64-bit `hash`, returning `true` when found.
532 ///
533 /// # Arguments
534 ///
535 /// - `u64` - Precomputed 64-bit hash of `key`.
536 /// - `&Q` - Borrowed key reference.
537 ///
538 /// # Returns
539 ///
540 /// - `bool` - `true` when the entry existed and was removed.
541 pub(crate) fn remove_by_hash<Q>(&mut self, hash: u64, key: &Q) -> bool
542 where
543 K: Borrow<Q>,
544 Q: Eq + ?Sized,
545 {
546 let cap: usize = self.get_ctrl().len();
547 if cap == 0 {
548 return false;
549 }
550 let mask: usize = cap - 1;
551 let h2: u8 = Self::h2_tag(hash);
552 let mut idx: usize = (hash as usize) & mask;
553 loop {
554 let tag: u8 = self.get_ctrl()[idx];
555 if tag == h2 {
556 if let Some(slot) = &self.get_slots()[idx]
557 && slot.get_hash() == hash
558 && slot.get_key().borrow() == key
559 {
560 self.get_mut_ctrl()[idx] = SLOT_TOMBSTONE;
561 self.get_mut_slots()[idx] = None;
562 let next_len: usize = self.len() - 1;
563 self.set_len(next_len);
564 let next_tombs: usize = self.get_tombstones() + 1;
565 self.set_tombstones(next_tombs);
566 return true;
567 }
568 } else if tag == SLOT_EMPTY {
569 return false;
570 }
571 idx = (idx + 1) & mask;
572 }
573 }
574
575 /// Evicts all idle entries according to `policy` at `now_ns`, returning the evicted count.
576 ///
577 /// # Arguments
578 ///
579 /// - `&RateLimitPolicy` - Active rate-limiting policy.
580 /// - `u64` - Current monotonic timestamp in nanoseconds.
581 ///
582 /// # Returns
583 ///
584 /// - `usize` - Number of idle entries removed.
585 pub(crate) fn retain_active(&mut self, policy: &RateLimitPolicy, now_ns: u64) -> usize {
586 let cap: usize = self.get_ctrl().len();
587 if cap == 0 || self.is_empty() {
588 return 0;
589 }
590 let mut removed: usize = 0;
591 let mut idx: usize = 0;
592 while idx < cap {
593 if self.get_ctrl()[idx] >= SLOT_OCCUPIED_BIT {
594 let is_idle: bool = match &self.get_slots()[idx] {
595 Some(slot) => policy.is_idle_atomic(slot.get_entry().get_state(), now_ns),
596 None => false,
597 };
598 if is_idle {
599 self.get_mut_ctrl()[idx] = SLOT_TOMBSTONE;
600 self.get_mut_slots()[idx] = None;
601 removed += 1;
602 }
603 }
604 idx += 1;
605 }
606 if removed > 0 {
607 let next_len: usize = self.len() - removed;
608 self.set_len(next_len);
609 if next_len == 0 {
610 self.get_mut_ctrl().fill(SLOT_EMPTY);
611 self.set_tombstones(0);
612 } else {
613 let next_tombs: usize = self.get_tombstones() + removed;
614 self.set_tombstones(next_tombs);
615 }
616 }
617 removed
618 }
619
620 /// Evicts the least-recently-used entry in place without cloning or re-hashing the key.
621 pub(crate) fn evict_oldest(&mut self) {
622 let cap: usize = self.get_ctrl().len();
623 let mut oldest_idx: Option<usize> = None;
624 let mut oldest_ts: u64 = u64::MAX;
625 let mut idx: usize = 0;
626 while idx < cap {
627 if self.get_ctrl()[idx] >= SLOT_OCCUPIED_BIT
628 && let Some(slot) = &self.get_slots()[idx]
629 {
630 let ts: u64 = slot.get_entry().load_last_seen_ns();
631 if oldest_idx.is_none() || ts < oldest_ts {
632 oldest_ts = ts;
633 oldest_idx = Some(idx);
634 }
635 }
636 idx += 1;
637 }
638 if let Some(evict_idx) = oldest_idx {
639 self.get_mut_ctrl()[evict_idx] = SLOT_TOMBSTONE;
640 self.get_mut_slots()[evict_idx] = None;
641 let next_len: usize = self.len() - 1;
642 self.set_len(next_len);
643 let next_tombs: usize = self.get_tombstones() + 1;
644 self.set_tombstones(next_tombs);
645 }
646 }
647
648 /// Removes all entries while retaining allocated slot capacity.
649 pub(crate) fn clear(&mut self) {
650 if self.is_empty() && self.get_tombstones() == 0 {
651 return;
652 }
653 self.get_mut_ctrl().fill(SLOT_EMPTY);
654 for slot in self.get_mut_slots().iter_mut() {
655 *slot = None;
656 }
657 self.set_len(0);
658 self.set_tombstones(0);
659 }
660}
661
662/// Accessors for `ReaderSlot`.
663impl ReaderSlot {
664 /// Creates a zeroed cache-line-isolated reader counter slot.
665 ///
666 /// # Returns
667 ///
668 /// - `Self` - Zeroed reader slot.
669 #[inline(always)]
670 pub(crate) const fn new() -> Self {
671 Self {
672 readers: AtomicU32::new(0),
673 }
674 }
675
676 /// Returns a reference to the atomic reader counter.
677 ///
678 /// # Returns
679 ///
680 /// - `&AtomicU32` - Reader count reference.
681 #[inline(always)]
682 pub(crate) fn get_readers(&self) -> &AtomicU32 {
683 &self.readers
684 }
685}
686
687/// Asymmetric reader-zero-sharing RW lock operations for `ShardRwLock`.
688impl<T> ShardRwLock<T> {
689 /// Creates a new unlocked `ShardRwLock` wrapping `value`.
690 ///
691 /// # Arguments
692 ///
693 /// - `T` - Protected shard state.
694 ///
695 /// # Returns
696 ///
697 /// - `Self` - Unlocked RW lock.
698 #[inline(always)]
699 pub(crate) const fn new(value: T) -> Self {
700 Self {
701 writer_flag: AtomicU32::new(0),
702 data: UnsafeCell::new(value),
703 }
704 }
705
706 /// Returns a reference to the exclusive writer flag.
707 ///
708 /// # Returns
709 ///
710 /// - `&AtomicU32` - Writer flag reference.
711 #[inline(always)]
712 fn get_writer_flag(&self) -> &AtomicU32 {
713 &self.writer_flag
714 }
715
716 /// Returns a reference to the protected `UnsafeCell`.
717 ///
718 /// # Returns
719 ///
720 /// - `&UnsafeCell<T>` - Cell reference.
721 #[inline(always)]
722 fn get_data(&self) -> &UnsafeCell<T> {
723 &self.data
724 }
725
726 /// Acquires a shared read lock using the caller's thread-local `ReaderSlot`.
727 ///
728 /// Executes zero writes to any shard-shared cache line when no writer is active.
729 ///
730 /// # Arguments
731 ///
732 /// - `&'a self` - The shard RW lock.
733 /// - `&'a ReaderSlot` - Caller's thread-local cache-line-isolated reader slot.
734 ///
735 /// # Returns
736 ///
737 /// - `ShardReadGuard<'a, T>` - Panic-safe shared read guard.
738 #[inline(always)]
739 pub(crate) fn read_with_slot<'a>(&'a self, slot: &'a ReaderSlot) -> ShardReadGuard<'a, T> {
740 slot.get_readers().fetch_add(1, Ordering::SeqCst);
741 if self.get_writer_flag().load(Ordering::SeqCst) == 0 {
742 return ShardReadGuard {
743 slot,
744 data: self.get_data().get() as *const T,
745 };
746 }
747 self.read_slow(slot)
748 }
749
750 /// Cold contention path for `read_with_slot` when a writer holds or drains the shard.
751 ///
752 /// # Arguments
753 ///
754 /// - `&'a self` - The shard RW lock.
755 /// - `&'a ReaderSlot` - Caller's thread-local reader slot.
756 ///
757 /// # Returns
758 ///
759 /// - `ShardReadGuard<'a, T>` - Panic-safe shared read guard.
760 #[cold]
761 #[inline(never)]
762 fn read_slow<'a>(&'a self, slot: &'a ReaderSlot) -> ShardReadGuard<'a, T> {
763 let readers: &AtomicU32 = slot.get_readers();
764 let writer_flag: &AtomicU32 = self.get_writer_flag();
765 readers.fetch_sub(1, Ordering::Release);
766 let mut spins: u32 = 0;
767 loop {
768 while writer_flag.load(Ordering::Acquire) != 0 {
769 spins += 1;
770 if spins < RW_SPIN_LIMIT {
771 spin_loop();
772 } else {
773 yield_now();
774 }
775 }
776 readers.fetch_add(1, Ordering::SeqCst);
777 if writer_flag.load(Ordering::SeqCst) == 0 {
778 return ShardReadGuard {
779 slot,
780 data: self.get_data().get() as *const T,
781 };
782 }
783 readers.fetch_sub(1, Ordering::Release);
784 }
785 }
786
787 /// Acquires an exclusive write lock and drains all active reader slots via Dekker ordering.
788 ///
789 /// # Arguments
790 ///
791 /// - `&[ReaderSlot]` - All per-thread reader slots belonging to the parent limiter.
792 ///
793 /// # Returns
794 ///
795 /// - `ShardWriteGuard<'_, T>` - Panic-safe exclusive write guard.
796 #[inline]
797 pub(crate) fn write_draining(&self, reader_slots: &[ReaderSlot]) -> ShardWriteGuard<'_, T> {
798 let writer_flag: &AtomicU32 = self.get_writer_flag();
799 let mut spins: u32 = 0;
800 while writer_flag
801 .compare_exchange_weak(0, 1, Ordering::SeqCst, Ordering::Relaxed)
802 .is_err()
803 {
804 spins += 1;
805 if spins < RW_SPIN_LIMIT {
806 spin_loop();
807 } else {
808 yield_now();
809 }
810 }
811 for slot in reader_slots {
812 let mut drain_spins: u32 = 0;
813 while slot.get_readers().load(Ordering::SeqCst) != 0 {
814 drain_spins += 1;
815 if drain_spins < RW_SPIN_LIMIT {
816 spin_loop();
817 } else {
818 yield_now();
819 }
820 }
821 }
822 ShardWriteGuard { lock: self }
823 }
824}
825
826unsafe impl<T: Send> Send for ShardRwLock<T> {}
827
828unsafe impl<T: Send + Sync> Sync for ShardRwLock<T> {}
829
830/// Debug formatting for `ShardRwLock`.
831impl<T: fmt::Debug> fmt::Debug for ShardRwLock<T> {
832 /// Formats lock status without acquiring reader slots.
833 ///
834 /// # Arguments
835 ///
836 /// - `&mut fmt::Formatter<'_>` - Target formatter.
837 ///
838 /// # Returns
839 ///
840 /// - `fmt::Result` - Formatting outcome.
841 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
842 f.debug_struct("ShardRwLock")
843 .field(
844 "writer_active",
845 &(self.get_writer_flag().load(Ordering::Relaxed) != 0),
846 )
847 .finish()
848 }
849}
850
851/// Accessors for `ShardReadGuard`.
852impl<'a, T> ShardReadGuard<'a, T> {
853 /// Returns a reference to the thread-local reader slot held by this guard.
854 ///
855 /// # Returns
856 ///
857 /// - `&'a ReaderSlot` - Reader slot reference.
858 #[inline(always)]
859 fn get_slot(&self) -> &'a ReaderSlot {
860 self.slot
861 }
862
863 /// Returns a raw pointer to the protected data.
864 ///
865 /// # Returns
866 ///
867 /// - `*const T` - Protected data pointer.
868 #[inline(always)]
869 fn get_data(&self) -> *const T {
870 self.data
871 }
872}
873
874/// Deref support for `ShardReadGuard`.
875impl<T> Deref for ShardReadGuard<'_, T> {
876 type Target = T;
877
878 /// Returns a shared reference to the protected shard map.
879 ///
880 /// # Returns
881 ///
882 /// - `&Self::Target` - Protected reference.
883 #[inline(always)]
884 fn deref(&self) -> &Self::Target {
885 unsafe { &*self.get_data() }
886 }
887}
888
889/// Release on drop for `ShardReadGuard`.
890impl<T> Drop for ShardReadGuard<'_, T> {
891 /// Releases one shared reader count on the thread-local slot with `Release` ordering.
892 #[inline(always)]
893 fn drop(&mut self) {
894 self.get_slot()
895 .get_readers()
896 .fetch_sub(1, Ordering::Release);
897 }
898}
899
900/// Accessors for `ShardWriteGuard`.
901impl<'a, T> ShardWriteGuard<'a, T> {
902 /// Returns a reference to the parent `ShardRwLock`.
903 ///
904 /// # Returns
905 ///
906 /// - `&'a ShardRwLock<T>` - Parent lock reference.
907 #[inline(always)]
908 fn get_lock(&self) -> &'a ShardRwLock<T> {
909 self.lock
910 }
911}
912
913/// Deref support for `ShardWriteGuard`.
914impl<T> Deref for ShardWriteGuard<'_, T> {
915 type Target = T;
916
917 /// Returns a shared reference to the protected shard map.
918 ///
919 /// # Returns
920 ///
921 /// - `&Self::Target` - Protected reference.
922 #[inline(always)]
923 fn deref(&self) -> &Self::Target {
924 unsafe { &*self.get_lock().get_data().get() }
925 }
926}
927
928/// DerefMut support for `ShardWriteGuard`.
929impl<T> DerefMut for ShardWriteGuard<'_, T> {
930 /// Returns an exclusive mutable reference to the protected shard map.
931 ///
932 /// # Returns
933 ///
934 /// - `&mut Self::Target` - Protected mutable reference.
935 #[inline(always)]
936 fn deref_mut(&mut self) -> &mut Self::Target {
937 unsafe { &mut *self.get_lock().get_data().get() }
938 }
939}
940
941/// Release on drop for `ShardWriteGuard`.
942impl<T> Drop for ShardWriteGuard<'_, T> {
943 /// Releases the exclusive writer flag with `Release` ordering.
944 #[inline(always)]
945 fn drop(&mut self) {
946 self.get_lock()
947 .get_writer_flag()
948 .store(0, Ordering::Release);
949 }
950}
951
952/// Partition accessors for `KeyedShard`.
953impl<K> KeyedShard<K> {
954 /// Creates an empty cache-line-aligned shard.
955 ///
956 /// # Returns
957 ///
958 /// - `Self` - Empty shard instance.
959 #[inline(always)]
960 pub(crate) const fn new() -> Self {
961 Self {
962 count: AtomicUsize::new(0),
963 map: ShardRwLock::new(ShardMap::new()),
964 }
965 }
966
967 /// Returns a reference to the atomic per-shard entry counter.
968 ///
969 /// # Returns
970 ///
971 /// - `&AtomicUsize` - Reference to per-shard entry count.
972 #[inline(always)]
973 pub(crate) fn get_count(&self) -> &AtomicUsize {
974 &self.count
975 }
976
977 /// Returns a reference to the shard `ShardRwLock`.
978 ///
979 /// # Returns
980 ///
981 /// - `&ShardRwLock<ShardMap<K>>` - Reference to the shard lock.
982 #[inline(always)]
983 pub(crate) fn get_map(&self) -> &ShardRwLock<ShardMap<K>> {
984 &self.map
985 }
986
987 /// Acquires a shared read guard on the shard map using `slot`.
988 ///
989 /// # Arguments
990 ///
991 /// - `&'a self` - The shard instance.
992 /// - `&'a ReaderSlot` - Caller's thread-local reader slot.
993 ///
994 /// # Returns
995 ///
996 /// - `ShardReadGuard<'a, ShardMap<K>>` - Shared read guard.
997 #[inline(always)]
998 pub(crate) fn read_map<'a>(&'a self, slot: &'a ReaderSlot) -> ShardReadGuard<'a, ShardMap<K>> {
999 self.get_map().read_with_slot(slot)
1000 }
1001
1002 /// Acquires an exclusive write guard on the shard map, draining all active readers.
1003 ///
1004 /// # Arguments
1005 ///
1006 /// - `&[ReaderSlot]` - All per-thread reader slots of the parent limiter.
1007 ///
1008 /// # Returns
1009 ///
1010 /// - `ShardWriteGuard<'_, ShardMap<K>>` - Exclusive write guard.
1011 #[inline(always)]
1012 pub(crate) fn write_map(
1013 &self,
1014 reader_slots: &[ReaderSlot],
1015 ) -> ShardWriteGuard<'_, ShardMap<K>> {
1016 self.get_map().write_draining(reader_slots)
1017 }
1018}
1019
1020/// Core 64-way sharded bounded rate-limiting operations for `KeyedRateLimiter`.
1021impl<K> KeyedRateLimiter<K>
1022where
1023 K: Eq + Hash,
1024{
1025 /// Creates a 64-way sharded bounded `KeyedRateLimiter` for the given `policy` and `max_entries`.
1026 ///
1027 /// # Arguments
1028 ///
1029 /// - `RateLimitPolicy` - Rate-limiting policy applied per key.
1030 /// - `usize` - Target maximum key capacity (`>= 1`).
1031 ///
1032 /// # Returns
1033 ///
1034 /// - `Result<Self, RateLimitError>` - Constructed limiter or `ZeroCapacity`.
1035 pub fn new(policy: RateLimitPolicy, max_entries: usize) -> Result<Self, RateLimitError> {
1036 Self::with_clock(policy, max_entries, MonotonicClock::new())
1037 }
1038
1039 /// Creates a 64-way sharded bounded `KeyedRateLimiter` anchored at `clock`.
1040 ///
1041 /// # Arguments
1042 ///
1043 /// - `RateLimitPolicy` - Rate-limiting policy applied per key.
1044 /// - `usize` - Target maximum key capacity (`>= 1`).
1045 /// - `MonotonicClock` - Monotonic clock origin.
1046 ///
1047 /// # Returns
1048 ///
1049 /// - `Result<Self, RateLimitError>` - Constructed limiter or `ZeroCapacity`.
1050 pub fn with_clock(
1051 policy: RateLimitPolicy,
1052 max_entries: usize,
1053 clock: MonotonicClock,
1054 ) -> Result<Self, RateLimitError> {
1055 if max_entries == 0 {
1056 return Err(RateLimitError::ZeroCapacity);
1057 }
1058 let per_shard_capacity: usize = max_entries.div_ceil(KEYED_SHARD_COUNT).max(1);
1059 let addr_entropy: u64 = (&policy as *const RateLimitPolicy) as usize as u64;
1060 let time_entropy: u64 = clock.now_ns();
1061 let hasher: FastBuildHasher =
1062 FastBuildHasher::new(addr_entropy ^ time_entropy.wrapping_mul(SEED_MIX_SALT));
1063 let mut reader_vec: Vec<ReaderSlot> = Vec::with_capacity(READER_SLOT_COUNT);
1064 let mut slot_idx: usize = 0;
1065 while slot_idx < READER_SLOT_COUNT {
1066 reader_vec.push(ReaderSlot::new());
1067 slot_idx += 1;
1068 }
1069 let mut shard_vec: Vec<KeyedShard<K>> = Vec::with_capacity(KEYED_SHARD_COUNT);
1070 let mut idx: usize = 0;
1071 while idx < KEYED_SHARD_COUNT {
1072 shard_vec.push(KeyedShard::new());
1073 idx += 1;
1074 }
1075 Ok(Self {
1076 policy,
1077 clock,
1078 hasher,
1079 max_entries,
1080 per_shard_capacity,
1081 total_len: AtomicUsize::new(0),
1082 reader_slots: reader_vec.into_boxed_slice(),
1083 shards: shard_vec.into_boxed_slice(),
1084 })
1085 }
1086
1087 /// Returns the configured rate-limiting policy.
1088 ///
1089 /// # Returns
1090 ///
1091 /// - `RateLimitPolicy` - Copy of the active policy.
1092 #[inline(always)]
1093 pub fn get_policy(&self) -> RateLimitPolicy {
1094 self.policy
1095 }
1096
1097 /// Returns a borrowed reference to the configured rate-limiting policy.
1098 ///
1099 /// # Returns
1100 ///
1101 /// - `&RateLimitPolicy` - Borrowed policy reference.
1102 #[inline(always)]
1103 pub(crate) fn get_policy_ref(&self) -> &RateLimitPolicy {
1104 &self.policy
1105 }
1106
1107 /// Returns the embedded monotonic clock.
1108 ///
1109 /// # Returns
1110 ///
1111 /// - `&MonotonicClock` - Reference to the clock.
1112 #[inline(always)]
1113 pub fn get_clock(&self) -> &MonotonicClock {
1114 &self.clock
1115 }
1116
1117 /// Returns the seeded internal hasher.
1118 ///
1119 /// # Returns
1120 ///
1121 /// - `&FastBuildHasher` - Reference to the build hasher.
1122 #[inline(always)]
1123 pub(crate) fn get_hasher(&self) -> &FastBuildHasher {
1124 &self.hasher
1125 }
1126
1127 /// Returns the caller-requested target entry capacity.
1128 ///
1129 /// # Returns
1130 ///
1131 /// - `usize` - Requested maximum entries.
1132 #[inline(always)]
1133 pub fn get_max_entries(&self) -> usize {
1134 self.max_entries
1135 }
1136
1137 /// Returns the hard entry capacity enforced per shard.
1138 ///
1139 /// # Returns
1140 ///
1141 /// - `usize` - Maximum entries per shard.
1142 #[inline(always)]
1143 pub fn get_per_shard_capacity(&self) -> usize {
1144 self.per_shard_capacity
1145 }
1146
1147 /// Returns the effective upper bound across all 64 shards (`64 * per_shard_capacity`).
1148 ///
1149 /// # Returns
1150 ///
1151 /// - `usize` - Total hard bound across all shards.
1152 #[inline(always)]
1153 pub fn effective_capacity(&self) -> usize {
1154 KEYED_SHARD_COUNT.saturating_mul(self.get_per_shard_capacity())
1155 }
1156
1157 /// Returns a reference to the atomic total entry count across all shards.
1158 ///
1159 /// # Returns
1160 ///
1161 /// - `&AtomicUsize` - Reference to the total live entry counter.
1162 #[inline(always)]
1163 pub(crate) fn get_total_len(&self) -> &AtomicUsize {
1164 &self.total_len
1165 }
1166
1167 /// Returns the slice of 32 cache-line-isolated per-thread reader slots.
1168 ///
1169 /// # Returns
1170 ///
1171 /// - `&[ReaderSlot]` - Reader slot slice.
1172 #[inline(always)]
1173 pub(crate) fn get_reader_slots(&self) -> &[ReaderSlot] {
1174 &self.reader_slots
1175 }
1176
1177 /// Returns the current thread's dedicated cache-line-isolated `ReaderSlot`.
1178 ///
1179 /// # Returns
1180 ///
1181 /// - `&ReaderSlot` - Thread-local reader counter slot.
1182 #[inline(always)]
1183 pub(crate) fn current_reader_slot(&self) -> &ReaderSlot {
1184 let slot_idx: usize = THREAD_READER_SLOT.with(|cell: &Cell<usize>| {
1185 let cached: usize = cell.get();
1186 if cached != READER_SLOT_UNINIT {
1187 return cached;
1188 }
1189 let assigned: usize =
1190 NEXT_READER_SLOT.fetch_add(1, Ordering::Relaxed) & READER_SLOT_MASK;
1191 cell.set(assigned);
1192 assigned
1193 });
1194 unsafe { self.get_reader_slots().get_unchecked(slot_idx) }
1195 }
1196
1197 /// Returns the slice of 64 shards.
1198 ///
1199 /// # Returns
1200 ///
1201 /// - `&[KeyedShard<K>]` - Shard slice.
1202 #[inline(always)]
1203 pub(crate) fn get_shards(&self) -> &[KeyedShard<K>] {
1204 &self.shards
1205 }
1206
1207 /// Computes `(hash, shard_index)` once for `key`, avoiding double hashing across shard and map.
1208 ///
1209 /// # Arguments
1210 ///
1211 /// - `&Q` - Borrowed key reference.
1212 ///
1213 /// # Returns
1214 ///
1215 /// - `(u64, usize)` - Precomputed 64-bit hash and shard index in `0..64`.
1216 #[inline(always)]
1217 pub(crate) fn hash_and_shard<Q>(&self, key: &Q) -> (u64, usize)
1218 where
1219 K: Borrow<Q>,
1220 Q: Eq + Hash + ?Sized,
1221 {
1222 let hash: u64 = self.get_hasher().hash_value(key);
1223 let shard_idx: usize = ((hash >> KEYED_SHARD_SHIFT) as usize) & KEYED_SHARD_MASK;
1224 (hash, shard_idx)
1225 }
1226
1227 /// Checks and consumes 1 unit for `key` using the embedded monotonic clock.
1228 ///
1229 /// # Arguments
1230 ///
1231 /// - `&Q` - Borrowed key reference (zero allocation on existing keys).
1232 ///
1233 /// # Returns
1234 ///
1235 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
1236 #[inline(always)]
1237 pub fn check<Q>(&self, key: &Q) -> RateLimitDecision
1238 where
1239 K: Borrow<Q>,
1240 Q: Eq + Hash + ToOwned<Owned = K> + ?Sized,
1241 {
1242 self.check_n_at_ns(key, self.get_clock().now_ns(), 1)
1243 }
1244
1245 /// Checks and consumes `cost` units for `key` using the embedded monotonic clock.
1246 ///
1247 /// # Arguments
1248 ///
1249 /// - `&Q` - Borrowed key reference (zero allocation on existing keys).
1250 /// - `u64` - Number of quota units to consume.
1251 ///
1252 /// # Returns
1253 ///
1254 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
1255 #[inline(always)]
1256 pub fn check_n<Q>(&self, key: &Q, cost: u64) -> RateLimitDecision
1257 where
1258 K: Borrow<Q>,
1259 Q: Eq + Hash + ToOwned<Owned = K> + ?Sized,
1260 {
1261 self.check_n_at_ns(key, self.get_clock().now_ns(), cost)
1262 }
1263
1264 /// Checks and consumes 1 unit for `key` at an explicit monotonic timestamp.
1265 ///
1266 /// # Arguments
1267 ///
1268 /// - `&Q` - Borrowed key reference.
1269 /// - `u64` - Monotonic timestamp in nanoseconds.
1270 ///
1271 /// # Returns
1272 ///
1273 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
1274 #[inline(always)]
1275 pub fn check_at_ns<Q>(&self, key: &Q, now_ns: u64) -> RateLimitDecision
1276 where
1277 K: Borrow<Q>,
1278 Q: Eq + Hash + ToOwned<Owned = K> + ?Sized,
1279 {
1280 self.check_n_at_ns(key, now_ns, 1)
1281 }
1282
1283 /// Checks and consumes `cost` units for `key` at an explicit monotonic timestamp.
1284 ///
1285 /// # Arguments
1286 ///
1287 /// - `&Q` - Borrowed key reference (zero allocation on existing keys).
1288 /// - `u64` - Monotonic timestamp in nanoseconds.
1289 /// - `u64` - Number of quota units to consume.
1290 ///
1291 /// # Returns
1292 ///
1293 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
1294 #[inline]
1295 pub fn check_n_at_ns<Q>(&self, key: &Q, now_ns: u64, cost: u64) -> RateLimitDecision
1296 where
1297 K: Borrow<Q>,
1298 Q: Eq + Hash + ToOwned<Owned = K> + ?Sized,
1299 {
1300 let policy: &RateLimitPolicy = self.get_policy_ref();
1301 let (hash, shard_idx): (u64, usize) = self.hash_and_shard(key);
1302 let shard: &KeyedShard<K> = unsafe { self.get_shards().get_unchecked(shard_idx) };
1303 let reader_slot: &ReaderSlot = self.current_reader_slot();
1304 {
1305 let guard: ShardReadGuard<'_, ShardMap<K>> = shard.read_map(reader_slot);
1306 if let Some(entry) = guard.get_by_hash(hash, key) {
1307 entry.touch(now_ns);
1308 return policy.check_n_atomic(entry.get_state(), now_ns, cost);
1309 }
1310 }
1311 self.check_n_at_ns_insert(shard, hash, key, now_ns, cost)
1312 }
1313
1314 /// Cold insertion and bounded-eviction path when `key` is absent from its shard.
1315 ///
1316 /// # Arguments
1317 ///
1318 /// - `&KeyedShard<K>` - Target shard partition.
1319 /// - `u64` - Precomputed 64-bit hash of `key`.
1320 /// - `&Q` - Borrowed key reference.
1321 /// - `u64` - Monotonic timestamp in nanoseconds.
1322 /// - `u64` - Number of quota units to consume.
1323 ///
1324 /// # Returns
1325 ///
1326 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
1327 #[cold]
1328 #[inline(never)]
1329 fn check_n_at_ns_insert<Q>(
1330 &self,
1331 shard: &KeyedShard<K>,
1332 hash: u64,
1333 key: &Q,
1334 now_ns: u64,
1335 cost: u64,
1336 ) -> RateLimitDecision
1337 where
1338 K: Borrow<Q>,
1339 Q: Eq + Hash + ToOwned<Owned = K> + ?Sized,
1340 {
1341 let policy: &RateLimitPolicy = self.get_policy_ref();
1342 let mut guard: ShardWriteGuard<'_, ShardMap<K>> = shard.write_map(self.get_reader_slots());
1343 if let Some(entry) = guard.get_by_hash(hash, key) {
1344 entry.touch(now_ns);
1345 return policy.check_n_atomic(entry.get_state(), now_ns, cost);
1346 }
1347 let prev_len: usize = guard.len();
1348 let cap: usize = self.get_per_shard_capacity();
1349 if prev_len >= cap {
1350 let _: usize = guard.retain_active(policy, now_ns);
1351 if guard.len() >= cap {
1352 guard.evict_oldest();
1353 }
1354 }
1355 let entry: KeyEntry = KeyEntry::new(policy.initial_state_at_ns(now_ns), now_ns);
1356 let decision: RateLimitDecision = policy.check_n_atomic(entry.get_state(), now_ns, cost);
1357 guard.insert_with_hash(hash, key.to_owned(), entry);
1358 let new_len: usize = guard.len();
1359 shard.get_count().store(new_len, Ordering::Relaxed);
1360 if new_len > prev_len {
1361 self.get_total_len()
1362 .fetch_add(new_len - prev_len, Ordering::Relaxed);
1363 } else if prev_len > new_len {
1364 self.get_total_len()
1365 .fetch_sub(prev_len - new_len, Ordering::Relaxed);
1366 }
1367 decision
1368 }
1369
1370 /// Inspects availability for `key` using the embedded clock without mutating or inserting state.
1371 ///
1372 /// # Arguments
1373 ///
1374 /// - `&Q` - Borrowed key reference.
1375 ///
1376 /// # Returns
1377 ///
1378 /// - `RateLimitDecision` - Non-mutating availability snapshot.
1379 #[inline(always)]
1380 pub fn peek<Q>(&self, key: &Q) -> RateLimitDecision
1381 where
1382 K: Borrow<Q>,
1383 Q: Eq + Hash + ?Sized,
1384 {
1385 self.peek_at_ns(key, self.get_clock().now_ns())
1386 }
1387
1388 /// Inspects availability for `key` at `now_ns` without mutating or inserting state.
1389 ///
1390 /// # Arguments
1391 ///
1392 /// - `&Q` - Borrowed key reference.
1393 /// - `u64` - Monotonic timestamp in nanoseconds.
1394 ///
1395 /// # Returns
1396 ///
1397 /// - `RateLimitDecision` - Non-mutating availability snapshot.
1398 #[inline(always)]
1399 pub fn peek_at_ns<Q>(&self, key: &Q, now_ns: u64) -> RateLimitDecision
1400 where
1401 K: Borrow<Q>,
1402 Q: Eq + Hash + ?Sized,
1403 {
1404 let policy: &RateLimitPolicy = self.get_policy_ref();
1405 let (hash, shard_idx): (u64, usize) = self.hash_and_shard(key);
1406 let shard: &KeyedShard<K> = unsafe { self.get_shards().get_unchecked(shard_idx) };
1407 let reader_slot: &ReaderSlot = self.current_reader_slot();
1408 let guard: ShardReadGuard<'_, ShardMap<K>> = shard.read_map(reader_slot);
1409 match guard.get_by_hash(hash, key) {
1410 Some(entry) => policy.peek_atomic(entry.get_state(), now_ns),
1411 None => policy.peek_absent_at_ns(now_ns),
1412 }
1413 }
1414
1415 /// Removes `key` from its shard if present.
1416 ///
1417 /// # Arguments
1418 ///
1419 /// - `&Q` - Borrowed key reference.
1420 ///
1421 /// # Returns
1422 ///
1423 /// - `bool` - `true` if the key existed and was removed.
1424 pub fn remove<Q>(&self, key: &Q) -> bool
1425 where
1426 K: Borrow<Q>,
1427 Q: Eq + Hash + ?Sized,
1428 {
1429 let (hash, shard_idx): (u64, usize) = self.hash_and_shard(key);
1430 let shard: &KeyedShard<K> = unsafe { self.get_shards().get_unchecked(shard_idx) };
1431 let mut guard: ShardWriteGuard<'_, ShardMap<K>> = shard.write_map(self.get_reader_slots());
1432 let removed: bool = guard.remove_by_hash(hash, key);
1433 if removed {
1434 shard.get_count().store(guard.len(), Ordering::Relaxed);
1435 self.get_total_len().fetch_sub(1, Ordering::Relaxed);
1436 }
1437 removed
1438 }
1439
1440 /// Evicts all currently idle entries across all 64 shards using the embedded monotonic clock.
1441 ///
1442 /// # Returns
1443 ///
1444 /// - `usize` - Total number of evicted keys.
1445 pub fn evict_idle(&self) -> usize {
1446 self.evict_idle_at_ns(self.get_clock().now_ns())
1447 }
1448
1449 /// Evicts all idle entries across all 64 shards at an explicit monotonic timestamp.
1450 ///
1451 /// # Arguments
1452 ///
1453 /// - `u64` - Monotonic timestamp in nanoseconds.
1454 ///
1455 /// # Returns
1456 ///
1457 /// - `usize` - Total number of evicted keys.
1458 pub fn evict_idle_at_ns(&self, now_ns: u64) -> usize {
1459 if self.is_empty() {
1460 return 0;
1461 }
1462 let policy: &RateLimitPolicy = self.get_policy_ref();
1463 let reader_slots: &[ReaderSlot] = self.get_reader_slots();
1464 let mut removed: usize = 0;
1465 for shard in self.get_shards() {
1466 if shard.get_count().load(Ordering::Relaxed) == 0 {
1467 continue;
1468 }
1469 let mut guard: ShardWriteGuard<'_, ShardMap<K>> = shard.write_map(reader_slots);
1470 let evicted: usize = guard.retain_active(policy, now_ns);
1471 if evicted > 0 {
1472 shard.get_count().store(guard.len(), Ordering::Relaxed);
1473 self.get_total_len().fetch_sub(evicted, Ordering::Relaxed);
1474 removed += evicted;
1475 }
1476 }
1477 removed
1478 }
1479
1480 /// Clears all tracked keys across all 64 shards.
1481 pub fn clear(&self) {
1482 if self.is_empty() {
1483 return;
1484 }
1485 let reader_slots: &[ReaderSlot] = self.get_reader_slots();
1486 for shard in self.get_shards() {
1487 if shard.get_count().load(Ordering::Relaxed) == 0 {
1488 continue;
1489 }
1490 let mut guard: ShardWriteGuard<'_, ShardMap<K>> = shard.write_map(reader_slots);
1491 let prev_len: usize = guard.len();
1492 guard.clear();
1493 shard.get_count().store(0, Ordering::Relaxed);
1494 if prev_len > 0 {
1495 self.get_total_len().fetch_sub(prev_len, Ordering::Relaxed);
1496 }
1497 }
1498 }
1499
1500 /// Returns the total number of tracked keys currently stored across all 64 shards.
1501 ///
1502 /// # Returns
1503 ///
1504 /// - `usize` - Approximate total entry count across shards.
1505 #[inline(always)]
1506 pub fn len(&self) -> usize {
1507 self.get_total_len().load(Ordering::Relaxed)
1508 }
1509
1510 /// Returns `true` if no keys are currently tracked across any shard.
1511 ///
1512 /// # Returns
1513 ///
1514 /// - `bool` - `true` when every shard is empty.
1515 #[inline(always)]
1516 pub fn is_empty(&self) -> bool {
1517 self.len() == 0
1518 }
1519}