Crates.io | rate-limit-macro |
lib.rs | rate-limit-macro |
version | 1.0.3 |
source | src |
created_at | 2023-09-12 04:44:31.39322 |
updated_at | 2023-11-06 22:18:01.637897 |
description | Procedural macro that provides a simple way to rate-limit blocks of code. |
homepage | |
repository | https://github.com/dkhokhlov/rate-limit-macro/tree/main/macro |
max_upload_size | |
id | 970446 |
size | 6,951 |
rate-limit-macro
is a procedural macro that provides a simple way to rate-limit blocks of code.
Add the following line to your Cargo.toml
under [dependencies]
:
rate-limit-macro = "1"
Here's a simple example:
use rate_limit_macro::rate_limit;
let mut called_times = 0;
for _ in 0..10 {
rate_limit!(rate = 5, interval = 1, {
called_times += 1;
});
}
// Only 5 calls should have been allowed due to rate limiting.
assert_eq!(called_times, 5);
You can also provide an optional fallback block that will be executed when the rate limit is exceeded:
let mut called_times = 0;
let mut fallback_called_times = 0;
for _ in 0..10 {
rate_limit!(rate = 5, interval = 1, {
called_times += 1;
}, {
fallback_called_times += 1;
});
}
// Check that the number of rate-limited calls and fallback calls add up to the total calls.
assert_eq!(called_times + fallback_called_times, 10);
rate
: The maximum number of times the block of code can be executed within the specified interval.interval
: The time interval (in seconds) for which the rate
applies.block
: The block of code to be rate-limited.fallback_block
(Optional): A block of code to be executed when the rate limit is exceeded.rate-limit-core
: This is a companion library that contains tests and depends on rate-limit-macro
.The source code for this crate is located in dkhokhlov/rate-limit-macro GitHub repository.
This crate is licensed under the MIT License.
If you'd like to contribute, please fork the repository and use a feature branch. Pull requests are warmly welcome.