leaky_bucket_lite/
lib.rs

1//! # leaky-bucket-lite
2//!
3//! [![docs badge][]][docs link]
4//! [![crates badge][]][crates link]
5//! [![actions badge][]][actions link]
6//!
7//! A token-based rate limiter based on the [leaky bucket] algorithm, mainly a lazy reimplementation of [udoprog's leaky-bucket] with less dependencies and overhead.
8//!
9//! If the tokens are already available, the acquisition will be instant through
10//! a fast path, and the acquired number of tokens will be added to the bucket.
11//!
12//! If they aren't, the task that tried to acquire the tokens will be suspended
13//! until the required number of tokens has been added.
14//!
15//! ## Usage
16//!
17//! Add the following to your `Cargo.toml`:
18//!
19//! ```toml
20//! leaky-bucket-lite = "0.5"
21//! ```
22//!
23//! ## Features
24//!
25//! leaky-bucket-lite provides 3 implementations:
26//!   * [`LeakyBucket`] (thread-safe, available via the `tokio` feature, which is on by default)
27//!   * [`sync_threadsafe::LeakyBucket`] (thread-safe, available via the `sync-threadsafe` feature)
28//!   * [`sync::LeakyBucket`] (not thread-safe, available via the `sync` feature).
29//!
30//! For potential performance increase with `sync-threadsafe` or `tokio` using [`parking_lot`]'s locking objects, enable the `parking_lot` feature.
31//!
32//! ## Example
33//!
34//! ```rust
35//! use leaky_bucket_lite::LeakyBucket;
36//! use std::time::Duration;
37//!
38//! #[tokio::main]
39//! async fn main() {
40//!     let rate_limiter = LeakyBucket::builder()
41//!         .max(5)
42//!         .tokens(0)
43//!         .refill_interval(Duration::from_secs(1))
44//!         .refill_amount(1)
45//!         .build();
46//!
47//!     println!("Waiting for permit...");
48//!     // should take about 5 seconds to acquire.
49//!     rate_limiter.acquire(5).await;
50//!     println!("I made it!");
51//! }
52//! ```
53//!
54//! [actions badge]: https://github.com/Gelbpunkt/leaky-bucket-lite/workflows/Rust/badge.svg
55//! [actions link]: https://github.com/Gelbpunkt/leaky-bucket-lite/actions
56//! [crates badge]: https://img.shields.io/crates/v/leaky-bucket-lite.svg
57//! [crates link]: https://crates.io/crates/leaky-bucket-lite
58//! [docs badge]: https://docs.rs/leaky-bucket-lite/badge.svg
59//! [docs link]: https://docs.rs/leaky-bucket-lite
60//! [leaky bucket]: https://en.wikipedia.org/wiki/Leaky_bucket
61//! [udoprog's leaky-bucket]: https://github.com/udoprog/leaky-bucket
62
63#![deny(
64    clippy::all,
65    clippy::missing_const_for_fn,
66    clippy::pedantic,
67    future_incompatible,
68    missing_docs,
69    nonstandard_style,
70    rust_2018_idioms,
71    rustdoc::broken_intra_doc_links,
72    unsafe_code,
73    unused,
74    warnings
75)]
76
77#[cfg(feature = "tokio")]
78mod tokio;
79#[cfg(feature = "tokio")]
80pub use crate::tokio::*;
81#[cfg(feature = "sync")]
82pub mod sync;
83#[cfg(feature = "sync-threadsafe")]
84pub mod sync_threadsafe;