pub struct TtlQueue<T> { /* private fields */ }
Expand description
A queue that drops its content after a given amount of time.
§Example
To implement an FPS counter, you could use the following technique:
let mut fps_counter = TtlQueue::new(Duration::from_secs_f64(1.0));
for i in 0..=50 {
// Register a new frame and return the number of frames observed
// within the last second.
let fps = fps_counter.refresh_and_push_back(());
debug_assert!(fps >= 1);
// Sleep ~20 ms to achieve a ~50 Hz frequency.
thread::sleep(Duration::from_millis(19));
}
let fps = fps_counter.refresh();
debug_assert!(fps >= 45 && fps <= 55);
let delta = fps_counter.avg_delta();
debug_assert!(delta >= Duration::from_millis(19) && delta <= Duration::from_millis(21));
Implementations§
Source§impl<T> TtlQueue<T>
impl<T> TtlQueue<T>
Sourcepub fn with_capacity(ttl: Duration, capacity: usize) -> Self
pub fn with_capacity(ttl: Duration, capacity: usize) -> Self
Creates an empty TtlQueue
for at least capacity
elements.
Sourcepub fn refresh_and_push_back(&mut self, element: T) -> usize
pub fn refresh_and_push_back(&mut self, element: T) -> usize
Pushes an element to the end of the queue and returns the number of items currently in the queue. This operation is O(N) at worst.
Sourcepub fn pop_front(&mut self) -> Option<(Instant, T)>
pub fn pop_front(&mut self) -> Option<(Instant, T)>
Gets the element from the front of the queue if it exists, as well as the time instant at which it was added.
Sourcepub fn peek_front(&mut self) -> Option<&(Instant, T)>
pub fn peek_front(&mut self) -> Option<&(Instant, T)>
Similar to pop_front
but without removing the element.
Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Gets the number elements currently in the queue, including potentially expired elements.
This operation is O(1). In order to obtain an accurate count in O(N) (worst-case),
use refresh
instead.
Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if the queue is definitely empty or false
if the queue is
possibly empty.
This operation is O(1). In order to obtain an accurate count in O(N) (worst-case),
use refresh
instead.