Struct CircularBuffer

Source
pub struct CircularBuffer<T: Clone> { /* private fields */ }
Expand description

Represents a FIFO CircularBuffer<T> data structure.

This structure is a limited capacity queue, with optional provisions for default values. Under normal circumstances, the size of the queue grows until it reaches its capacity, at which point any further additions push out its oldest member.

If default values are specified, then the size of the queue is always equal to its capacity, with empty slots occupied by the specified default value.

§Type parameters

  • T: Any type that implements the Clone trait.

§Examples

let mut cbuf = CircularBuffer::<isize>::new(3);
let mut cbuf_def = CircularBuffer::with_default(3, 0isize);

// Check sizes
assert_eq!(cbuf.size(), 0);
assert_eq!(cbuf_def.size(), 3);

// Add elements
cbuf.add(6);
cbuf_def.add(7);

// Peek at the next element scheduled for removal
assert_eq!(cbuf.peek().unwrap(), 6);
assert_eq!(cbuf_def.peek().unwrap(), 0);

Implementations§

Source§

impl<T: Clone> CircularBuffer<T>

Source

pub fn new(capacity: usize) -> CircularBuffer<T>

Default CircularBuffer<T> initializer

§Returns

A new, empty CircularBuffer<T>

§Examples
let cbuf: CircularBuffer<isize> = CircularBuffer::new(3);
assert_eq!(cbuf.size(), 0);
assert_eq!(cbuf.capacity(), 3);
Examples found in repository?
examples/cbuf.rs (line 11)
5fn main() {
6    println!("\nCircular buffer - typical usage");
7    println!("--");
8
9    println!("\nCreate an empty circular buffer with capacity 5:");
10    println!("let mut cbuf: CircularBuffer<isize> = CircularBuffer::new(5);");
11    let mut cbuf: CircularBuffer<isize> = CircularBuffer::new(5);
12
13    println!("\nAdd elements to it:");
14    println!("cbuf.add(1);");
15    println!("> {:?}", cbuf.add(1));
16    println!("cbuf.add(-2);");
17    println!("> {:?}", cbuf.add(-2));
18    println!("cbuf.add(3);");
19    println!("> {:?}", cbuf.add(3));
20
21    println!("\nCheck the buffer's size:");
22    println!("cbuf.size();  // Should be 3");
23    println!("> {}", cbuf.size());
24
25    println!("\nRemove elements from it:");
26    println!("cbuf.remove();  // Should be Ok(1)");
27    println!("> {:?}", cbuf.remove());
28
29    println!("\nCheck the buffer's size:");
30    println!("cbuf.size();  // Should be 2");
31    println!("> {}", cbuf.size());
32
33    println!("\nPeek at the next element to be removed:");
34    println!("cbuf.peek();  // Should be Ok(-2)");
35    println!("> {:?}", cbuf.peek());
36
37    println!("\nFill the buffer:");
38    println!("cbuf.add(-7);");
39    println!("> {:?}", cbuf.add(-7));
40    println!("cbuf.add(8);");
41    println!("> {:?}", cbuf.add(8));
42    println!("cbuf.add(-9);");
43    println!("> {:?}", cbuf.add(-9));
44
45    println!("\nCheck the buffer's size:");
46    println!("cbuf.size();  // Should be 5");
47    println!("> {}", cbuf.size());
48
49    println!("\nAdd a new element to the buffer:");
50    println!("cbuf.add(10);  // Should be OK(Some(-2))");
51    println!("{:?}", cbuf.add(10));
52
53    println!("\nCheck the buffer's size:");
54    println!("cbuf.size();  // Should still be 5");
55    println!("> {}", cbuf.size());
56
57    println!("\n--\n");
58}
Source

pub fn with_default(capacity: usize, default_value: T) -> CircularBuffer<T>

Create a CircularBuffer<T> with default values

§Returns

A new CircularBuffer<T> filled with default values

§Examples
let cbuf_def = CircularBuffer::with_default(3, -1isize);
assert_eq!(cbuf_def.size(), 3);
assert_eq!(cbuf_def.capacity(), 3);
assert_eq!(cbuf_def.peek(), Ok(-1));
Examples found in repository?
examples/cbuf_def.rs (line 11)
5fn main() {
6    println!("\nCircular buffer with default values - typical usage");
7    println!("--");
8
9    println!("\nCreate a circular buffer with capacity 3 and default -1:");
10    println!("let mut cbuf_def: CircularBuffer<isize> = CircularBuffer::with_default(3, -1);");
11    let mut cbuf_def: CircularBuffer<isize> = CircularBuffer::with_default(3, -1);
12
13    println!("\nCheck the buffer's size - should always be equal to the capacity:");
14    println!("cbuf_def.size();  // Should be 3");
15    println!("> {}", cbuf_def.size());
16
17    println!("\nPeek at the next element to be removed:");
18    println!("cbuf_def.peek();  // Should be Ok(-1)");
19    println!("> {:?}", cbuf_def.peek());
20
21    println!("\nAdd a new element to the buffer:");
22    println!("cbuf_def.add(45);  // Should be Ok(Some(-1))");
23    println!("{:?}", cbuf_def.add(45));
24
25    println!("\nPeek at the next element to be removed:");
26    println!("cbuf_def.peek();  // Should be Ok(-1)");
27    println!("> {:?}", cbuf_def.peek());
28
29    println!("\nFill the buffer:");
30    println!("cbuf_def.add(56);");
31    println!("> {:?}", cbuf_def.add(56));
32    println!("cbuf_def.add(67);");
33    println!("> {:?}", cbuf_def.add(67));
34
35    println!("\nPeek at the next element to be removed:");
36    println!("cbuf_def.peek();  // Should be Ok(45)");
37    println!("> {:?}", cbuf_def.peek());
38
39    println!("\nEmpty the buffer:");
40    println!("cbuf_def.remove();");
41    println!("{:?}", cbuf_def.remove());
42    println!("cbuf_def.remove();");
43    println!("{:?}", cbuf_def.remove());
44    println!("cbuf_def.remove();");
45    println!("{:?}", cbuf_def.remove());
46
47    println!("\nConfirm the buffer's size:");
48    println!("cbuf_def.size();  // Should be 3");
49    println!("> {}", cbuf_def.size());
50
51    println!("\nPeek at the next element to be removed:");
52    println!("cbuf_def.peek();  // Should be Ok(-1)");
53    println!("> {:?}", cbuf_def.peek());
54
55    println!("\n--\n");
56}
Source

pub fn capacity(&self) -> usize

Gets the capacity of the CircularBuffer<T>

§Returns

The number of allowed elements in the buffer

§Examples
let mut cbuf: CircularBuffer<isize> = CircularBuffer::new(3);
assert_eq!(cbuf.capacity(), 3);

Trait Implementations§

Source§

impl<T: Debug + Clone> Debug for CircularBuffer<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Clone> IsQueue<T> for CircularBuffer<T>

Source§

fn add(&mut self, val: T) -> Result<Option<T>, &str>

Adds an element to a circular buffer

§Parameters
  • val: Value to add to the buffer
§Returns
  • Ok(Some(T)): The oldest value in the buffer, in case the addition causes an overflow.
  • Ok(None): Nothing, if the buffer has room for the added element
§Examples
let mut cbuf: CircularBuffer<isize> = CircularBuffer::new(3);
let mut cbuf_def = CircularBuffer::with_default(3, 5isize);
assert_eq!(cbuf.add(42), Ok(None));
assert_eq!(cbuf_def.add(42), Ok(Some(5)));
Source§

fn remove(&mut self) -> Result<T, &str>

Removes an element from the circular buffer and returns it.

For circular buffers with default values, removing an element will add a new default value into the buffer.

§Returns
  • Ok(T): The oldest element in the buffer
  • Error
§Errors

Returns an error if an attempt is made to remove an element from an empty buffer

§Examples
let mut cbuf: CircularBuffer<isize> = CircularBuffer::new(3);
cbuf.add(42);
assert_eq!(cbuf.remove(), Ok(42));
assert_eq!(cbuf.size(), 0);

let mut cbuf_def = CircularBuffer::with_default(3, 4isize);
cbuf_def.add(42);
assert_eq!(cbuf_def.remove(), Ok(4));
Source§

fn peek(&self) -> Result<T, &str>

Peek at the head of the circular buffer

§Returns
  • Ok(T): The next element scheduled for removal from the buffer
  • Error
§Errors

Returns an error if an attempt is made to peek into an empty buffer

§Examples
let mut cbuf: CircularBuffer<isize> = CircularBuffer::new(3);
cbuf.add(42);
assert_eq!(cbuf.peek(), Ok(42));
Source§

fn size(&self) -> usize

Gets the size of the circular buffer

§Returns

The number of elements in the buffer. Note, this includes default values, which means that the size of a buffer with default values should always be equal to its capacity

§Examples
let mut cbuf: CircularBuffer<isize> = CircularBuffer::new(3);
assert_eq!(cbuf.size(), 0);
cbuf.add(42);
assert_eq!(cbuf.size(), 1);

Auto Trait Implementations§

§

impl<T> Freeze for CircularBuffer<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for CircularBuffer<T>
where T: RefUnwindSafe,

§

impl<T> Send for CircularBuffer<T>
where T: Send,

§

impl<T> Sync for CircularBuffer<T>
where T: Sync,

§

impl<T> Unpin for CircularBuffer<T>
where T: Unpin,

§

impl<T> UnwindSafe for CircularBuffer<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.