generational_cache/vector/impls/
array.rs

1//! Module provinding a vector implementation based on arrays.
2
3use crate::vector::Vector;
4use core::{
5    marker::Copy,
6    ops::{Deref, DerefMut},
7};
8
9/// Implements [`Vector`] with `[T; N]`.
10pub struct Array<T, const N: usize> {
11    buffer: [T; N],
12    len: usize,
13}
14
15impl<T, const N: usize> Array<T, N> {
16    /// Creates an [`Array`] with the given buffer.
17    pub fn with_buffer(buffer: [T; N]) -> Self {
18        Self { buffer, len: 0 }
19    }
20}
21
22impl<T, const N: usize> Array<T, N>
23where
24    T: Copy + Default,
25{
26    /// Creates a new [`Array`].
27    pub fn new() -> Self {
28        Self::with_buffer([Default::default(); N])
29    }
30}
31
32impl<T, const N: usize> Default for Array<T, N>
33where
34    T: Copy + Default,
35{
36    fn default() -> Self {
37        Self::new()
38    }
39}
40
41impl<T, const N: usize> DerefMut for Array<T, N> {
42    fn deref_mut(&mut self) -> &mut Self::Target {
43        &mut self.buffer[0..self.len]
44    }
45}
46
47impl<T, const N: usize> Deref for Array<T, N> {
48    type Target = [T];
49
50    fn deref(&self) -> &Self::Target {
51        &self.buffer[0..self.len]
52    }
53}
54
55/// Error assocaited with operations on [`Array`]
56#[derive(PartialEq, Debug)]
57pub enum ArrayError {
58    /// Used when attempting to push en element into an [`Array`] when it's at capacity.
59    OutOfMemory,
60}
61
62impl<T, const N: usize> Vector<T> for Array<T, N> {
63    type Error = ArrayError;
64
65    fn reserve(&mut self, additional: usize) -> Result<(), Self::Error> {
66        let remaining = self.capacity() - self.len();
67
68        if additional > remaining {
69            Err(ArrayError::OutOfMemory)
70        } else {
71            Ok(())
72        }
73    }
74
75    fn capacity(&self) -> usize {
76        N
77    }
78
79    fn push(&mut self, item: T) -> Result<(), Self::Error> {
80        if self.len() == self.capacity() {
81            Err(Self::Error::OutOfMemory)
82        } else {
83            self.buffer[self.len] = item;
84            self.len += 1;
85            Ok(())
86        }
87    }
88
89    fn clear(&mut self) {
90        self.len = 0;
91    }
92}