bottomless_pit/
buffer.rs

1//! The buffer struct indended for things like input buffers
2
3use std::ops::{Index, IndexMut};
4use std::slice::Iter;
5
6/// A buffer than can contain any type and at a specific length
7#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
8pub struct Buffer<T, const N: usize> {
9    inner: [T; N],
10}
11
12impl<T, const N: usize> Buffer<T, N> {
13    /// Creates a buffer with the starting data provided
14    pub fn new(inital_data: [T; N]) -> Self {
15        Self { inner: inital_data }
16    }
17
18    /// This adds a new entry into the buffer and deletes
19    /// the oldest entry in the buffer this operation in O(n),
20    pub fn insert_data(&mut self, data: T) {
21        self.inner.rotate_right(1);
22        self[0] = data;
23    }
24
25    /// Gives an iterator with the contents of the buffer for functional
26    /// operations
27    pub fn iter(&self) -> Iter<'_, T> {
28        self.inner.iter()
29    }
30
31    /// Returns the length of the buffer
32    pub fn len(&self) -> usize {
33        N
34    }
35
36    /// Buffers can never be empty this always be false
37    pub fn is_empty(&self) -> bool {
38        false
39    }
40}
41
42impl<T, const N: usize> Index<usize> for Buffer<T, N> {
43    type Output = T;
44    fn index(&self, index: usize) -> &Self::Output {
45        &self.inner[index]
46    }
47}
48
49impl<T, const N: usize> IndexMut<usize> for Buffer<T, N> {
50    fn index_mut(&mut self, index: usize) -> &mut T {
51        &mut self.inner[index]
52    }
53}
54
55impl<T, const N: usize> IntoIterator for Buffer<T, N> {
56    type Item = T;
57
58    type IntoIter = <[T; N] as IntoIterator>::IntoIter;
59
60    fn into_iter(self) -> Self::IntoIter {
61        self.inner.into_iter()
62    }
63}
64
65impl<'a, T, const N: usize> IntoIterator for &'a Buffer<T, N> {
66    type Item = &'a T;
67
68    type IntoIter = Iter<'a, T>;
69
70    fn into_iter(self) -> Self::IntoIter {
71        self.iter()
72    }
73}