make a ring buffer in rust

Here is an implementation of a ring buffer in Rust:

main.rs
pub struct RingBuffer<T> {
    head: usize,
    tail: usize,
    buffer: Vec<Option<T>>,
}

impl<T> RingBuffer<T> {
    pub fn new(size: usize) -> RingBuffer<T> {
        RingBuffer {
            head: 0,
            tail: 0,
            buffer: vec![None; size],
        }
    }

    pub fn push(&mut self, item: T) {
        if self.buffer[self.head].is_some() {
            self.tail = (self.tail + 1) % self.buffer.len();
        }
        self.buffer[self.head] = Some(item);
        self.head = (self.head + 1) % self.buffer.len();
    }

    pub fn pop(&mut self) -> Option<T> {
        if self.buffer[self.tail].is_none() {
            return None;
        }
        let item = self.buffer[self.tail].take();
        self.tail = (self.tail + 1) % self.buffer.len();
        item
    }
}
795 chars
33 lines

The new function creates a new ring buffer with the specified size. The push function adds an item to the buffer, wrapping around to the beginning if necessary. The pop function removes and returns the oldest item from the buffer.

related categories

gistlibby LogSnag