pub struct TimeWindow { /* private fields */ }Expand description
Time window for tracking events within a specific time period.
§Examples
use chie_shared::TimeWindow;
let mut window = TimeWindow::new(1000, 100); // 1 second window, max 100 events
// Track events at different timestamps
window.add_event(1000);
window.add_event(1100);
window.add_event(1200);
// Count events within the window
assert_eq!(window.count_events(1500), 3);
// Events older than window size are cleaned up
assert_eq!(window.count_events(2500), 0);
// Check rate limiting
let mut limiter = TimeWindow::new(1000, 5);
for i in 0..5 {
limiter.add_event(1000 + i * 10);
}
assert!(limiter.would_exceed_limit(1050, 5));Implementations§
Source§impl TimeWindow
impl TimeWindow
Sourcepub fn new(window_size_ms: u64, max_events: usize) -> Self
pub fn new(window_size_ms: u64, max_events: usize) -> Self
Create a new time window.
§Arguments
window_size_ms- Window size in millisecondsmax_events- Maximum number of events to track
Sourcepub fn count_events(&mut self, now_ms: i64) -> usize
pub fn count_events(&mut self, now_ms: i64) -> usize
Get the count of events within the window from the given timestamp.
Sourcepub fn would_exceed_limit(&mut self, now_ms: i64, limit: usize) -> bool
pub fn would_exceed_limit(&mut self, now_ms: i64, limit: usize) -> bool
Check if adding a new event would exceed the given limit.
Sourcepub fn events_per_second(&mut self, now_ms: i64) -> f64
pub fn events_per_second(&mut self, now_ms: i64) -> f64
Get events per second rate.
Sourcepub fn oldest_event_age_ms(&self, now_ms: i64) -> Option<u64>
pub fn oldest_event_age_ms(&self, now_ms: i64) -> Option<u64>
Get the age of the oldest event in milliseconds.
Trait Implementations§
Source§impl Clone for TimeWindow
impl Clone for TimeWindow
Source§fn clone(&self) -> TimeWindow
fn clone(&self) -> TimeWindow
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreAuto Trait Implementations§
impl Freeze for TimeWindow
impl RefUnwindSafe for TimeWindow
impl Send for TimeWindow
impl Sync for TimeWindow
impl Unpin for TimeWindow
impl UnwindSafe for TimeWindow
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