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
use super::*;
/// Configuration constructors and accessors for `TokenBucketConfig`.
impl TokenBucketConfig {
/// Builds a `TokenBucketConfig` refilling `refill_tokens` every `refill_period_ns` nanoseconds.
///
/// # Arguments
///
/// - `u64` - Maximum bucket capacity (`1..=u32::MAX`).
/// - `u64` - Tokens added per refill period (`>= 1`).
/// - `u64` - Refill period duration in nanoseconds (`>= 1`).
///
/// # Returns
///
/// - `Result<Self, RateLimitError>` - Validated configuration or an error.
#[inline(always)]
pub fn from_nanos(
capacity: u64,
refill_tokens: u64,
refill_period_ns: u64,
) -> Result<Self, RateLimitError> {
if capacity == 0 || capacity > MAX_TOKEN_BUCKET_CAPACITY {
return Err(RateLimitError::InvalidCapacity);
}
if refill_tokens == 0 {
return Err(RateLimitError::ZeroRate);
}
if refill_period_ns == 0 {
return Err(RateLimitError::ZeroPeriod);
}
let divisor: u64 = Self::gcd_u64(refill_tokens, refill_period_ns);
let step_tokens: u64 = refill_tokens / divisor;
let step_ns: u64 = refill_period_ns / divisor;
let step_ns_div: FastDivU64 = FastDivU64::new(step_ns);
let step_tokens_div: FastDivU64 = FastDivU64::new(step_tokens);
let token_bits: u32 = (TOKEN_STATE_BITS - capacity.leading_zeros()).max(1);
let token_mask: u64 = (1u64 << token_bits) - 1;
let step_bits: u32 = TOKEN_STATE_BITS - token_bits;
let step_mask: u64 = (1u64 << step_bits) - 1;
let step_half: u64 = 1u64 << (step_bits - 1);
Ok(Self {
capacity,
step_tokens,
step_ns,
step_ns_div,
step_tokens_div,
token_bits,
token_mask,
step_mask,
step_half,
})
}
/// Builds a `TokenBucketConfig` refilling `refill_tokens` every `refill_period`.
///
/// # Arguments
///
/// - `u64` - Maximum bucket capacity (`1..=u32::MAX`).
/// - `u64` - Tokens added per refill period (`>= 1`).
/// - `Duration` - Refill period duration (`>= 1ns`).
///
/// # Returns
///
/// - `Result<Self, RateLimitError>` - Validated configuration or an error.
#[inline(always)]
pub fn new(
capacity: u64,
refill_tokens: u64,
refill_period: Duration,
) -> Result<Self, RateLimitError> {
let nanos: u128 = refill_period.as_nanos();
if nanos == 0 {
return Err(RateLimitError::ZeroPeriod);
}
if nanos > u64::MAX as u128 {
return Err(RateLimitError::Overflow);
}
Self::from_nanos(capacity, refill_tokens, nanos as u64)
}
/// Builds a `TokenBucketConfig` refilling `tokens_per_sec` tokens every second.
///
/// # Arguments
///
/// - `u64` - Maximum bucket capacity (`1..=u32::MAX`).
/// - `u64` - Sustained tokens added per second (`>= 1`).
///
/// # Returns
///
/// - `Result<Self, RateLimitError>` - Validated configuration or an error.
#[inline(always)]
pub fn per_second(capacity: u64, tokens_per_sec: u64) -> Result<Self, RateLimitError> {
Self::from_nanos(capacity, tokens_per_sec, TOKEN_NANOS_PER_SEC)
}
/// Returns the maximum token capacity of the bucket.
///
/// # Arguments
///
/// - `&Self` - The token-bucket configuration.
///
/// # Returns
///
/// - `u64` - Maximum token capacity.
#[inline(always)]
pub fn get_capacity(&self) -> u64 {
self.capacity
}
/// Returns the reduced token increment per refill step.
///
/// # Arguments
///
/// - `&Self` - The token-bucket configuration.
///
/// # Returns
///
/// - `u64` - Tokens replenished per step.
#[inline(always)]
pub fn get_step_tokens(&self) -> u64 {
self.step_tokens
}
/// Returns the reduced refill step interval in nanoseconds.
///
/// # Arguments
///
/// - `&Self` - The token-bucket configuration.
///
/// # Returns
///
/// - `u64` - Step duration in nanoseconds.
#[inline(always)]
pub fn get_step_ns(&self) -> u64 {
self.step_ns
}
/// Returns the precomputed reciprocal divider for `step_ns`.
///
/// # Returns
///
/// - `&FastDivU64` - Reciprocal divider reference.
#[inline(always)]
pub(crate) fn get_step_ns_div(&self) -> &FastDivU64 {
&self.step_ns_div
}
/// Returns the precomputed reciprocal divider for `step_tokens`.
///
/// # Returns
///
/// - `&FastDivU64` - Reciprocal divider reference.
#[inline(always)]
pub(crate) fn get_step_tokens_div(&self) -> &FastDivU64 {
&self.step_tokens_div
}
/// Computes exact `now_ns / step_ns` without hardware division.
///
/// # Arguments
///
/// - `u64` - Monotonic timestamp in nanoseconds.
///
/// # Returns
///
/// - `u64` - Refill step index.
#[inline(always)]
pub(crate) fn div_step_ns(&self, now_ns: u64) -> u64 {
self.get_step_ns_div().div(now_ns)
}
/// Computes exact `tokens / step_tokens` without hardware division.
///
/// # Arguments
///
/// - `u64` - Token numerator.
///
/// # Returns
///
/// - `u64` - Exact quotient.
#[inline(always)]
pub(crate) fn div_step_tokens(&self, tokens: u64) -> u64 {
self.get_step_tokens_div().div(tokens)
}
/// Returns the bit width reserved for the packed token count.
///
/// # Arguments
///
/// - `&Self` - The token-bucket configuration.
///
/// # Returns
///
/// - `u32` - Token counter bit width.
#[inline(always)]
pub(crate) fn get_token_bits(&self) -> u32 {
self.token_bits
}
/// Returns the bitmask extracting the packed token count.
///
/// # Arguments
///
/// - `&Self` - The token-bucket configuration.
///
/// # Returns
///
/// - `u64` - Token counter bitmask.
#[inline(always)]
pub(crate) fn get_token_mask(&self) -> u64 {
self.token_mask
}
/// Returns the bitmask wrapping the refill step index.
///
/// # Arguments
///
/// - `&Self` - The token-bucket configuration.
///
/// # Returns
///
/// - `u64` - Step index bitmask.
#[inline(always)]
pub(crate) fn get_step_mask(&self) -> u64 {
self.step_mask
}
/// Returns the half-ring threshold for modular step ordering.
///
/// # Arguments
///
/// - `&Self` - The token-bucket configuration.
///
/// # Returns
///
/// - `u64` - Half-ring step threshold.
#[inline(always)]
pub(crate) fn get_step_half(&self) -> u64 {
self.step_half
}
/// Computes the greatest common divisor of two non-zero `u64` values via Euclid's algorithm.
///
/// # Arguments
///
/// - `u64` - First positive integer.
/// - `u64` - Second positive integer.
///
/// # Returns
///
/// - `u64` - Greatest common divisor.
#[inline(always)]
pub(crate) fn gcd_u64(mut a: u64, mut b: u64) -> u64 {
while b != 0 {
let rem: u64 = a % b;
a = b;
b = rem;
}
a
}
}
/// Lock-free atomic token-bucket operations on `TokenBucketCell`.
impl TokenBucketCell {
/// Creates a `TokenBucketCell` starting full according to `config`.
///
/// # Arguments
///
/// - `&TokenBucketConfig` - Token-bucket configuration.
#[inline(always)]
pub fn full(config: &TokenBucketConfig) -> Self {
Self {
packed: AtomicU64::new(config.get_capacity()),
}
}
/// Creates a `TokenBucketCell` starting with `initial_tokens` clamped to `config.get_capacity()`.
///
/// # Arguments
///
/// - `&TokenBucketConfig` - Token-bucket configuration.
/// - `u64` - Starting number of available tokens.
#[inline(always)]
pub fn with_initial_tokens(config: &TokenBucketConfig, initial_tokens: u64) -> Self {
let clamped: u64 = initial_tokens.min(config.get_capacity());
Self {
packed: AtomicU64::new(clamped),
}
}
/// Returns a reference to the packed atomic word.
///
/// # Arguments
///
/// - `&Self` - The token-bucket cell.
///
/// # Returns
///
/// - `&AtomicU64` - Reference to the packed state word.
#[inline(always)]
pub(crate) fn get_packed(&self) -> &AtomicU64 {
&self.packed
}
/// Resets the bucket to full capacity anchored at `now_ns`.
///
/// # Arguments
///
/// - `&Self` - The token-bucket cell.
/// - `&TokenBucketConfig` - Token-bucket configuration.
/// - `u64` - Current monotonic timestamp in nanoseconds.
#[inline(always)]
pub fn reset_at_ns(&self, config: &TokenBucketConfig, now_ns: u64) {
let step_low: u64 = config.div_step_ns(now_ns) & config.get_step_mask();
let next: u64 = (step_low << config.get_token_bits()) | config.get_capacity();
self.get_packed().store(next, Ordering::Release);
}
/// Returns whether the bucket is completely full at `now_ns`.
///
/// # Arguments
///
/// - `&Self` - The token-bucket cell.
/// - `&TokenBucketConfig` - Token-bucket configuration.
/// - `u64` - Current monotonic timestamp in nanoseconds.
///
/// # Returns
///
/// - `bool` - `true` when available tokens equal configured capacity.
#[inline(always)]
pub fn is_idle_at_ns(&self, config: &TokenBucketConfig, now_ns: u64) -> bool {
Self::is_idle_atomic(self.get_packed(), config, now_ns)
}
/// Inspects current token availability at `now_ns` without consuming tokens.
///
/// # Arguments
///
/// - `&Self` - The token-bucket cell.
/// - `&TokenBucketConfig` - Token-bucket configuration.
/// - `u64` - Current monotonic timestamp in nanoseconds.
///
/// # Returns
///
/// - `RateLimitDecision` - Non-mutating availability snapshot.
#[inline(always)]
pub fn peek_at_ns(&self, config: &TokenBucketConfig, now_ns: u64) -> RateLimitDecision {
Self::peek_atomic(self.get_packed(), config, now_ns)
}
/// Atomically checks and consumes `cost` tokens at monotonic timestamp `now_ns`.
///
/// # Arguments
///
/// - `&Self` - The token-bucket cell.
/// - `&TokenBucketConfig` - Token-bucket configuration.
/// - `u64` - Current monotonic timestamp in nanoseconds.
/// - `u64` - Number of tokens to consume.
///
/// # Returns
///
/// - `RateLimitDecision` - Admission decision and nanosecond timings.
#[inline(always)]
pub fn check_n_at_ns(
&self,
config: &TokenBucketConfig,
now_ns: u64,
cost: u64,
) -> RateLimitDecision {
Self::check_n_atomic(self.get_packed(), config, now_ns, cost)
}
/// Atomically adds up to `tokens` back into the bucket, saturating at capacity.
///
/// # Arguments
///
/// - `&Self` - The token-bucket cell.
/// - `&TokenBucketConfig` - Token-bucket configuration.
/// - `u64` - Current monotonic timestamp in nanoseconds.
/// - `u64` - Number of tokens to refund.
///
/// # Returns
///
/// - `u64` - Available token count after refunding.
#[inline(always)]
pub fn refund_at_ns(&self, config: &TokenBucketConfig, now_ns: u64, tokens: u64) -> u64 {
let capacity: u64 = config.get_capacity();
let token_bits: u32 = config.get_token_bits();
let step_mask: u64 = config.get_step_mask();
let cur_step_low: u64 = config.div_step_ns(now_ns) & step_mask;
let atomic: &AtomicU64 = self.get_packed();
let mut current: u64 = atomic.load(Ordering::Relaxed);
loop {
let (ahead_steps, available): (u64, u64) =
Self::resolve_tokens_at(config, current, cur_step_low);
let next_tokens: u64 = available.saturating_add(tokens).min(capacity);
let next_step_low: u64 = cur_step_low.wrapping_add(ahead_steps) & step_mask;
let next_packed: u64 = (next_step_low << token_bits) | next_tokens;
match atomic.compare_exchange_weak(
current,
next_packed,
Ordering::Relaxed,
Ordering::Relaxed,
) {
Ok(_) => return next_tokens,
Err(observed) => {
current = observed;
}
}
}
}
/// Checks whether a raw packed atomic token-bucket word is full at `now_ns`.
///
/// # Arguments
///
/// - `&AtomicU64` - Atomic packed state word.
/// - `&TokenBucketConfig` - Token-bucket configuration.
/// - `u64` - Current monotonic timestamp in nanoseconds.
///
/// # Returns
///
/// - `bool` - `true` when available tokens equal capacity.
#[inline(always)]
pub(crate) fn is_idle_atomic(
atomic: &AtomicU64,
config: &TokenBucketConfig,
now_ns: u64,
) -> bool {
let state: u64 = atomic.load(Ordering::Relaxed);
let cur_step_low: u64 = config.div_step_ns(now_ns) & config.get_step_mask();
let (_, available): (u64, u64) = Self::resolve_tokens_at(config, state, cur_step_low);
available >= config.get_capacity()
}
/// Non-mutating token-bucket availability check against a raw atomic word.
///
/// # Arguments
///
/// - `&AtomicU64` - Atomic packed state word.
/// - `&TokenBucketConfig` - Token-bucket configuration.
/// - `u64` - Current monotonic timestamp in nanoseconds.
///
/// # Returns
///
/// - `RateLimitDecision` - Availability snapshot.
#[inline(always)]
pub(crate) fn peek_atomic(
atomic: &AtomicU64,
config: &TokenBucketConfig,
now_ns: u64,
) -> RateLimitDecision {
let state: u64 = atomic.load(Ordering::Relaxed);
let step_ns: u64 = config.get_step_ns();
let cur_step_full: u64 = config.div_step_ns(now_ns);
let base_rem_ns: u64 = step_ns - (now_ns - cur_step_full.wrapping_mul(step_ns));
let (ahead_steps, available): (u64, u64) =
Self::resolve_tokens_at(config, state, cur_step_full & config.get_step_mask());
let capacity: u64 = config.get_capacity();
let reset_after_ns: u64 =
Self::time_until_tokens_at(config, ahead_steps, base_rem_ns, available, capacity);
let allowed: bool = available >= 1;
let retry_after_ns: u64 = if allowed {
0
} else {
Self::time_until_tokens_at(config, ahead_steps, base_rem_ns, available, 1)
};
RateLimitDecision::new(allowed, available, reset_after_ns, retry_after_ns, capacity)
}
/// Lock-free token-bucket check and consumption against a raw atomic word.
///
/// # Arguments
///
/// - `&AtomicU64` - Atomic packed state word.
/// - `&TokenBucketConfig` - Token-bucket configuration.
/// - `u64` - Current monotonic timestamp in nanoseconds.
/// - `u64` - Number of tokens to consume.
///
/// # Returns
///
/// - `RateLimitDecision` - Admission decision and nanosecond timings.
#[inline(always)]
pub(crate) fn check_n_atomic(
atomic: &AtomicU64,
config: &TokenBucketConfig,
now_ns: u64,
cost: u64,
) -> RateLimitDecision {
let capacity: u64 = config.get_capacity();
let token_bits: u32 = config.get_token_bits();
let step_mask: u64 = config.get_step_mask();
let step_ns: u64 = config.get_step_ns();
let cur_step_full: u64 = config.div_step_ns(now_ns);
let cur_step_low: u64 = cur_step_full & step_mask;
let base_rem_ns: u64 = step_ns - (now_ns - cur_step_full.wrapping_mul(step_ns));
if cost == 0 {
let state: u64 = atomic.load(Ordering::Relaxed);
let (ahead_steps, available): (u64, u64) =
Self::resolve_tokens_at(config, state, cur_step_low);
let reset_after_ns: u64 =
Self::time_until_tokens_at(config, ahead_steps, base_rem_ns, available, capacity);
return RateLimitDecision::new(true, available, reset_after_ns, 0, capacity);
}
if cost > capacity {
let state: u64 = atomic.load(Ordering::Relaxed);
let (ahead_steps, available): (u64, u64) =
Self::resolve_tokens_at(config, state, cur_step_low);
let reset_after_ns: u64 =
Self::time_until_tokens_at(config, ahead_steps, base_rem_ns, available, capacity);
return RateLimitDecision::new(false, available, reset_after_ns, u64::MAX, capacity);
}
let mut current: u64 = atomic.load(Ordering::Relaxed);
loop {
let (ahead_steps, available): (u64, u64) =
Self::resolve_tokens_at(config, current, cur_step_low);
if available < cost {
let reset_after_ns: u64 = Self::time_until_tokens_at(
config,
ahead_steps,
base_rem_ns,
available,
capacity,
);
let retry_after_ns: u64 =
Self::time_until_tokens_at(config, ahead_steps, base_rem_ns, available, cost);
return RateLimitDecision::new(
false,
available,
reset_after_ns,
retry_after_ns,
capacity,
);
}
let remaining: u64 = available - cost;
let next_step_low: u64 = cur_step_low.wrapping_add(ahead_steps) & step_mask;
let next_packed: u64 = (next_step_low << token_bits) | remaining;
match atomic.compare_exchange_weak(
current,
next_packed,
Ordering::Relaxed,
Ordering::Relaxed,
) {
Ok(_) => {
let reset_after_ns: u64 = Self::time_until_tokens_at(
config,
ahead_steps,
base_rem_ns,
remaining,
capacity,
);
return RateLimitDecision::new(true, remaining, reset_after_ns, 0, capacity);
}
Err(observed) => {
current = observed;
}
}
}
}
/// Resolves `(ahead_steps, available_tokens)` against precomputed `cur_step_low`.
///
/// # Arguments
///
/// - `&TokenBucketConfig` - Token-bucket configuration.
/// - `u64` - Loaded packed state word.
/// - `u64` - Masked current step index (`cur_step_full & step_mask`).
///
/// # Returns
///
/// - `(u64, u64)` - Tuple of `(ahead_steps, available_tokens)`.
#[inline(always)]
pub(crate) fn resolve_tokens_at(
config: &TokenBucketConfig,
packed: u64,
cur_step_low: u64,
) -> (u64, u64) {
let stored_step_low: u64 = packed >> config.get_token_bits();
let stored_tokens: u64 = packed & config.get_token_mask();
if stored_step_low == cur_step_low {
return (0, stored_tokens);
}
let forward_diff: u64 = cur_step_low.wrapping_sub(stored_step_low) & config.get_step_mask();
if forward_diff < config.get_step_half() {
let added: u64 = forward_diff.saturating_mul(config.get_step_tokens());
let available: u64 = stored_tokens
.saturating_add(added)
.min(config.get_capacity());
(0, available)
} else {
let ahead_diff: u64 =
stored_step_low.wrapping_sub(cur_step_low) & config.get_step_mask();
(ahead_diff, stored_tokens)
}
}
/// Computes nanoseconds until the bucket reaches at least `target_tokens` in pure 64-bit math.
///
/// # Arguments
///
/// - `&TokenBucketConfig` - Token-bucket configuration.
/// - `u64` - Steps ahead of `cur_step_full` (`0` in monotonic forward flow).
/// - `u64` - Nanoseconds remaining in the current step (`1..=step_ns`).
/// - `u64` - Currently available tokens.
/// - `u64` - Desired token level.
///
/// # Returns
///
/// - `u64` - Nanoseconds until `target_tokens` will be available.
#[inline(always)]
pub(crate) fn time_until_tokens_at(
config: &TokenBucketConfig,
ahead_steps: u64,
base_rem_ns: u64,
available: u64,
target_tokens: u64,
) -> u64 {
if available >= target_tokens {
return 0;
}
let needed: u64 = target_tokens - available;
let steps_needed: u64 = if config.get_step_tokens() == 1 {
needed
} else {
1 + config.div_step_tokens(needed - 1)
};
let total_steps: u64 = ahead_steps.saturating_add(steps_needed);
base_rem_ns.saturating_add((total_steps - 1).saturating_mul(config.get_step_ns()))
}
}
/// Core lock-free operations for `TokenBucketLimiter`.
impl TokenBucketLimiter {
/// Creates a new full `TokenBucketLimiter` from a validated `TokenBucketConfig`.
///
/// # Arguments
///
/// - `TokenBucketConfig` - Validated token-bucket configuration.
#[inline(always)]
pub fn new(config: TokenBucketConfig) -> Self {
let cell: TokenBucketCell = TokenBucketCell::full(&config);
Self {
config,
clock: MonotonicClock::new(),
cell,
}
}
/// Creates a `TokenBucketLimiter` starting with `initial_tokens` clamped to capacity.
///
/// # Arguments
///
/// - `TokenBucketConfig` - Validated token-bucket configuration.
/// - `u64` - Initial token count.
#[inline(always)]
pub fn with_initial_tokens(config: TokenBucketConfig, initial_tokens: u64) -> Self {
let cell: TokenBucketCell = TokenBucketCell::with_initial_tokens(&config, initial_tokens);
Self {
config,
clock: MonotonicClock::new(),
cell,
}
}
/// Creates a `TokenBucketLimiter` anchored at a caller-supplied `MonotonicClock`.
///
/// # Arguments
///
/// - `TokenBucketConfig` - Validated token-bucket configuration.
/// - `MonotonicClock` - Monotonic clock origin.
#[inline(always)]
pub fn with_clock(config: TokenBucketConfig, clock: MonotonicClock) -> Self {
let cell: TokenBucketCell = TokenBucketCell::full(&config);
Self {
config,
clock,
cell,
}
}
/// Creates a full `TokenBucketLimiter` refilling `tokens_per_sec` tokens every second.
///
/// # Arguments
///
/// - `u64` - Maximum bucket capacity (`1..=u32::MAX`).
/// - `u64` - Tokens added per second (`>= 1`).
///
/// # Returns
///
/// - `Result<Self, RateLimitError>` - Constructed limiter or configuration error.
#[inline(always)]
pub fn per_second(capacity: u64, tokens_per_sec: u64) -> Result<Self, RateLimitError> {
let config: TokenBucketConfig = TokenBucketConfig::per_second(capacity, tokens_per_sec)?;
Ok(Self::new(config))
}
/// Returns the token-bucket configuration.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
///
/// # Returns
///
/// - `&TokenBucketConfig` - Reference to the configuration.
#[inline(always)]
pub fn get_config(&self) -> &TokenBucketConfig {
&self.config
}
/// Returns the embedded monotonic clock.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
///
/// # Returns
///
/// - `&MonotonicClock` - Reference to the clock.
#[inline(always)]
pub fn get_clock(&self) -> &MonotonicClock {
&self.clock
}
/// Returns a reference to the underlying atomic token-bucket cell.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
///
/// # Returns
///
/// - `&TokenBucketCell` - Reference to the atomic cell.
#[inline(always)]
pub(crate) fn get_cell(&self) -> &TokenBucketCell {
&self.cell
}
/// Checks and consumes 1 token using the embedded monotonic clock.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
///
/// # Returns
///
/// - `RateLimitDecision` - Admission decision and nanosecond timings.
#[inline(always)]
pub fn check(&self) -> RateLimitDecision {
self.check_n_at_ns(self.get_clock().now_ns(), 1)
}
/// Checks and consumes `cost` tokens using the embedded monotonic clock.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
/// - `u64` - Number of tokens to consume.
///
/// # Returns
///
/// - `RateLimitDecision` - Admission decision and nanosecond timings.
#[inline(always)]
pub fn check_n(&self, cost: u64) -> RateLimitDecision {
self.check_n_at_ns(self.get_clock().now_ns(), cost)
}
/// Checks and consumes 1 token at an explicit monotonic timestamp in nanoseconds.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
/// - `u64` - Monotonic timestamp in nanoseconds.
///
/// # Returns
///
/// - `RateLimitDecision` - Admission decision and nanosecond timings.
#[inline(always)]
pub fn check_at_ns(&self, now_ns: u64) -> RateLimitDecision {
self.get_cell().check_n_at_ns(self.get_config(), now_ns, 1)
}
/// Checks and consumes `cost` tokens at an explicit monotonic timestamp in nanoseconds.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
/// - `u64` - Monotonic timestamp in nanoseconds.
/// - `u64` - Number of tokens to consume.
///
/// # Returns
///
/// - `RateLimitDecision` - Admission decision and nanosecond timings.
#[inline(always)]
pub fn check_n_at_ns(&self, now_ns: u64, cost: u64) -> RateLimitDecision {
self.get_cell()
.check_n_at_ns(self.get_config(), now_ns, cost)
}
/// Inspects current availability without consuming tokens.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
///
/// # Returns
///
/// - `RateLimitDecision` - Non-mutating availability snapshot.
#[inline(always)]
pub fn peek(&self) -> RateLimitDecision {
self.peek_at_ns(self.get_clock().now_ns())
}
/// Inspects availability at an explicit monotonic timestamp without consuming tokens.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
/// - `u64` - Monotonic timestamp in nanoseconds.
///
/// # Returns
///
/// - `RateLimitDecision` - Non-mutating availability snapshot.
#[inline(always)]
pub fn peek_at_ns(&self, now_ns: u64) -> RateLimitDecision {
self.get_cell().peek_at_ns(self.get_config(), now_ns)
}
/// Refunds `tokens` back into the bucket using the embedded monotonic clock.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
/// - `u64` - Number of tokens to add back.
///
/// # Returns
///
/// - `u64` - Available token count after refunding.
#[inline(always)]
pub fn refund(&self, tokens: u64) -> u64 {
self.refund_at_ns(self.get_clock().now_ns(), tokens)
}
/// Refunds `tokens` back into the bucket at an explicit monotonic timestamp.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
/// - `u64` - Monotonic timestamp in nanoseconds.
/// - `u64` - Number of tokens to add back.
///
/// # Returns
///
/// - `u64` - Available token count after refunding.
#[inline(always)]
pub fn refund_at_ns(&self, now_ns: u64, tokens: u64) -> u64 {
self.get_cell()
.refund_at_ns(self.get_config(), now_ns, tokens)
}
/// Resets the bucket back to full capacity at the current monotonic time.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
#[inline(always)]
pub fn reset(&self) {
self.reset_at_ns(self.get_clock().now_ns());
}
/// Resets the bucket back to full capacity at an explicit monotonic timestamp.
///
/// # Arguments
///
/// - `&Self` - The limiter instance.
/// - `u64` - Monotonic timestamp in nanoseconds.
#[inline(always)]
pub fn reset_at_ns(&self, now_ns: u64) {
self.get_cell().reset_at_ns(self.get_config(), now_ns);
}
}