1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use core::mem::MaybeUninit;

/// A fixed size ring buffer
pub struct RingBuffer<T, const N: usize> {
    buffer: [MaybeUninit<T>; N],
    read_index: usize,
    write_index: usize,
}

#[allow(dead_code)]
impl<T, const N: usize> RingBuffer<T, N> {
    pub fn try_push(&mut self, value: T) -> bool {
        let next_index = (self.write_index + 1) % self.buffer.len();
        if next_index == self.read_index {
            return false;
        }

        self.buffer[self.write_index] = MaybeUninit::new(value);
        self.write_index = next_index;

        true
    }

    pub fn push(&mut self, value: T) {
        let next_index = (self.write_index + 1) % self.buffer.len();
        if next_index == self.read_index {
            panic!("Ring buffer overflow");
        }

        self.buffer[self.write_index] = MaybeUninit::new(value);
        self.write_index = next_index;
    }

    pub fn push_replace(&mut self, value: T) {
        let next_index = (self.write_index + 1) % self.buffer.len();
        // if the buffer is full, replace the oldest value
        if next_index == self.read_index {
            // drop the oldest value
            unsafe { self.buffer[self.read_index].assume_init_drop() };
            self.buffer[self.read_index] = MaybeUninit::new(value);
            self.write_index = next_index;
            // advance the read index
            self.read_index = (self.read_index + 1) % self.buffer.len();
        } else {
            self.buffer[self.write_index] = MaybeUninit::new(value);
            self.write_index = next_index;
        }
    }

    pub fn pop(&mut self) -> Option<T> {
        if self.read_index == self.write_index {
            return None;
        }

        let value = unsafe { self.buffer[self.read_index].assume_init_read() };
        self.read_index = (self.read_index + 1) % self.buffer.len();

        Some(value)
    }

    pub fn clear(&mut self) {
        self.read_index = 0;
        self.write_index = 0;
    }
}

#[allow(dead_code)]
impl<T: Copy, const N: usize> RingBuffer<T, N> {
    pub const fn empty() -> Self {
        Self {
            buffer: [MaybeUninit::<T>::uninit(); N],
            read_index: 0,
            write_index: 0,
        }
    }
}