pub struct FixedWindowCounter { /* private fields */ }Expand description
A Fixed Window Counter rate limiter.
This implementation uses fixed time windows to limit the number of requests within each window. It’s simple to understand and implement, but can allow twice the rate of requests around window boundaries.
§Features
- Uses fixed time windows for rate limiting.
- Allows a specified number of requests within each time window.
- Automatically clears old windows to prevent memory growth.
§Example
use std::time::Duration;
use limitr::window::FixedWindowCounter;
let mut counter = FixedWindowCounter::new(100, Duration::from_secs(60));
for _ in 0..100 {
assert!(counter.try_consume().await);
}
assert!(!counter.try_consume().await);Implementations§
Source§impl FixedWindowCounter
impl FixedWindowCounter
Sourcepub fn new(limit: u32, window_duration: Duration) -> Self
pub fn new(limit: u32, window_duration: Duration) -> Self
Creates a new FixedWindowCounter with the specified limit and window_duration.
limit: The maximum number of requests allowed in each time window.window_duration: The duration of each time window.
§Example
use std::time::Duration;
use limitr::window::FixedWindowCounter;
let counter = FixedWindowCounter::new(100, Duration::from_secs(60)); // 100 requests per minuteSourcepub async fn try_consume(&self) -> bool
pub async fn try_consume(&self) -> bool
Attempts to consume a token from the current time window.
Returns true if the request is allowed, and false if the limit has been reached for the current window.
§Example
use std::time::Duration;
use limitr::window::FixedWindowCounter;
let mut counter = FixedWindowCounter::new(5, Duration::from_secs(60));
for _ in 0..5 {
assert!(counter.try_consume().await);
}
assert!(!counter.try_consume().await);Sourcepub async fn clear_old_windows(&self)
pub async fn clear_old_windows(&self)
Clears old time windows to prevent unbounded growth of the internal HashMap.
This method should be called periodically to remove data for expired time windows.
§Example
use std::time::Duration;
use limitr::window::FixedWindowCounter;
let mut counter = FixedWindowCounter::new(100, Duration::from_secs(60));
// ... some time passes ...
counter.clear_old_windows().await;Auto Trait Implementations§
impl !Freeze for FixedWindowCounter
impl !RefUnwindSafe for FixedWindowCounter
impl Send for FixedWindowCounter
impl Sync for FixedWindowCounter
impl Unpin for FixedWindowCounter
impl UnwindSafe for FixedWindowCounter
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more