TokenBucket
A token-bucket rate limiter with the clock passed in.
The bucket holds up to capacity tokens and gets refill_per_second new ones every second.
Each action takes tokens with try_acquire; when there are not enough
left the action is refused, so bursts up to capacity are allowed while the long-run rate
stays at refill_per_second. Nothing here reads a clock: pass the current time in
milliseconds (any monotonic count works). A time that goes backwards is treated as no time
having passed.
Import
Section titled “Import”Cargo feature function (enabled by default). To compile only this module:
or in Cargo.toml:
Definition
Section titled “Definition”Examples
Section titled “Examples”Methods
Section titled “Methods”Creates a full bucket.
Parameters
| Parameter | Type | Description |
|---|---|---|
capacity | u32 | The most tokens the bucket holds, which is also the largest burst. |
refill_per_second | u32 | How many tokens are added every second. |
now_ms | u64 | The current time in milliseconds. |
Returns
Self — A bucket holding capacity tokens.
try_acquire
Section titled “try_acquire”Takes one token if there is one.
Parameters
| Parameter | Type | Description |
|---|---|---|
now_ms | u64 | The current time in milliseconds. |
Returns
bool — true when a token was taken, false when the bucket is empty.
try_acquire_n
Section titled “try_acquire_n”Takes tokens tokens at once if that many are available, and none otherwise.
Parameters
| Parameter | Type | Description |
|---|---|---|
now_ms | u64 | The current time in milliseconds. |
tokens | u32 | How many tokens the action costs. |
Returns
bool — true when the tokens were taken, false when there are not enough (nothing is taken).
available
Section titled “available”How many whole tokens are available right now.
Parameters
| Parameter | Type | Description |
|---|---|---|
now_ms | u64 | The current time in milliseconds. |
Returns
u32 — The number of tokens that try_acquire_n would grant at once.
