|
| 1 | +#![feature(generic_const_exprs)] |
| 2 | +#![allow(incomplete_features)] |
| 3 | + |
| 4 | +pub enum Restriction<const V: bool = true> {} |
| 5 | +pub trait Valid {} |
| 6 | + |
| 7 | +impl Valid for Restriction<true> {} |
| 8 | + |
| 9 | +/** |
| 10 | + a circular buffer |
| 11 | +*/ |
| 12 | +pub struct CircularBuffer<T, const S: usize> { |
| 13 | + buffer: Vec<T>, |
| 14 | + index: usize, |
| 15 | +} |
| 16 | + |
| 17 | +impl<T, const S: usize> CircularBuffer<T, { S }> |
| 18 | +where |
| 19 | + Restriction<{ S > 0 }>: Valid, |
| 20 | +{ |
| 21 | + /** |
| 22 | + create a new [`CircularBuffer`] instance |
| 23 | + */ |
| 24 | + pub fn new() -> Self { |
| 25 | + Self { |
| 26 | + buffer: Vec::with_capacity(S), |
| 27 | + index: S - 1, |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + push a value onto the buffer |
| 33 | + */ |
| 34 | + pub fn push(&mut self, value: T) { |
| 35 | + self.index = self.index.checked_add(1).unwrap_or(0) % S; |
| 36 | + match self.count() < self.capacity() { |
| 37 | + true => self.buffer.insert(self.index, value), |
| 38 | + false => self.buffer[self.index] = value, |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + push a value onto the buffer |
| 44 | + */ |
| 45 | + pub fn pop(&mut self) -> Result<T, CircularBufferError> { |
| 46 | + if self.count() == 0 { |
| 47 | + Err(CircularBufferError::Underflow)? |
| 48 | + } |
| 49 | + |
| 50 | + let old = self.buffer.remove(self.index); |
| 51 | + self.index = self.index.checked_sub(1).unwrap_or(S - 1); |
| 52 | + Ok(old) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl<T, const S: usize> CircularBuffer<T, { S }> { |
| 57 | + /** |
| 58 | + returns the current count of the buffer |
| 59 | + */ |
| 60 | + pub fn count(&self) -> usize { |
| 61 | + self.buffer.len() |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + returns the max capacity of the buffer |
| 66 | + */ |
| 67 | + pub const fn capacity(&self) -> usize { |
| 68 | + S |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +impl<T, const S: usize> CircularBuffer<T, { S }> |
| 73 | +where |
| 74 | + T: Clone, |
| 75 | +{ |
| 76 | + /** |
| 77 | + take the values in a vec, leaving an empty buffer |
| 78 | + */ |
| 79 | + pub fn take(&mut self) -> Vec<T> { |
| 80 | + let mut buf = Vec::with_capacity(self.buffer.len()); |
| 81 | + buf.copy_from_slice(self.buffer[..]); |
| 82 | + self.index = S - 1; |
| 83 | + buf |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + returns true if the buffer is empty |
| 88 | + */ |
| 89 | + pub fn is_empty(&self) -> bool { |
| 90 | + self.buffer.is_empty() |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +#[derive(Debug, PartialEq)] |
| 95 | +pub enum CircularBufferError { |
| 96 | + /// attempted to pop when buffer is empty |
| 97 | + Underflow, |
| 98 | +} |
| 99 | + |
| 100 | +fn main() {} |
0 commit comments