#block #limit #rate-limiting #proc-macro #procedural

macro rate-limit-macro

Procedural macro that provides a simple way to rate-limit blocks of code

4 stable releases

1.0.3 Nov 6, 2023
1.0.1 Sep 12, 2023

#99 in #limit

Download history 8/week @ 2024-08-04 9/week @ 2024-08-11 14/week @ 2024-08-18 2/week @ 2024-08-25 11/week @ 2024-09-22 5/week @ 2024-09-29

112 downloads per month
Used in rate-limit-core

MIT license

7KB
66 lines

Rate-Limit-Macro

Introduction

rate-limit-macro is a procedural macro that provides a simple way to rate-limit blocks of code.

Installation

Add the following line to your Cargo.toml under [dependencies]:

rate-limit-macro = "1"

Usage

Basic Usage

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);

With Fallback Block

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);

API Documentation

  • 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.

Notes

  • This macro is lockless, so rate limiting is not absolutely exact.
  • rate-limit-core: This is a companion library that contains tests and depends on rate-limit-macro.

Source Code

The source code for this crate is located in dkhokhlov/rate-limit-macro GitHub repository.

License

This crate is licensed under the MIT License.

Authors

Contributing

If you'd like to contribute, please fork the repository and use a feature branch. Pull requests are warmly welcome.

Dependencies

~245–700KB
~17K SLoC