Struct tui_logger::CircularBuffer
source · pub struct CircularBuffer<T> { /* private fields */ }
Expand description
CircularBuffer is used to store the last elements of an endless sequence. Oldest elements will be overwritten. The implementation focus on speed. So memory allocations are avoided.
Usage example:
extern crate tui_logger;
use tui_logger::CircularBuffer;
let mut cb : CircularBuffer<u64> = CircularBuffer::new(5);
cb.push(1);
cb.push(2);
cb.push(3);
cb.push(4);
cb.push(5);
cb.push(6); // This will overwrite the first element
// Total elements pushed into the buffer is 6.
assert_eq!(6,cb.total_elements());
// Thus the buffer has wrapped around.
assert_eq!(true,cb.has_wrapped());
/// Iterate through the elements:
{
let mut iter = cb.iter();
assert_eq!(Some(&2), iter.next());
assert_eq!(Some(&3), iter.next());
assert_eq!(Some(&4), iter.next());
assert_eq!(Some(&5), iter.next());
assert_eq!(Some(&6), iter.next());
assert_eq!(None, iter.next());
}
/// Iterate backwards through the elements:
{
let mut iter = cb.rev_iter();
assert_eq!(Some(&6), iter.next());
assert_eq!(Some(&5), iter.next());
assert_eq!(Some(&4), iter.next());
assert_eq!(Some(&3), iter.next());
assert_eq!(Some(&2), iter.next());
assert_eq!(None, iter.next());
}
// The elements in the buffer are now:
assert_eq!(vec![2,3,4,5,6],cb.take());
// After taking all elements, the buffer is empty.
let now_empty : Vec<u64> = vec![];
assert_eq!(now_empty,cb.take());
Implementations§
source§impl<T> CircularBuffer<T>
impl<T> CircularBuffer<T>
sourcepub fn new(max_depth: usize) -> CircularBuffer<T>
pub fn new(max_depth: usize) -> CircularBuffer<T>
Create a new CircularBuffer, which can hold max_depth elements
sourcepub fn push(&mut self, elem: T)
pub fn push(&mut self, elem: T)
Push a new element into the buffer. Until the capacity is reached, elements are pushed. Afterwards the oldest elements will be overwritten.
sourcepub fn take(&mut self) -> Vec<T>
pub fn take(&mut self) -> Vec<T>
Take out all elements from the buffer, leaving an empty buffer behind
sourcepub fn total_elements(&self) -> usize
pub fn total_elements(&self) -> usize
Total number of elements pushed into the buffer.
sourcepub fn has_wrapped(&self) -> bool
pub fn has_wrapped(&self) -> bool
If has_wrapped() is true, then elements have been overwritten