generational_cache/vector/impls/
alloc_vec.rs

1//! Module providing a vector implementation based on [`alloc::vec::Vec`].
2
3extern crate alloc;
4
5use crate::vector::Vector;
6use alloc::vec::Vec;
7use core::{
8    convert::Infallible,
9    ops::{Deref, DerefMut},
10};
11
12/// Implements [`Vector`] with [`alloc::vec::Vec`].
13pub struct AllocVec<T> {
14    vec: Vec<T>,
15}
16
17impl<T> Default for AllocVec<T> {
18    fn default() -> Self {
19        Self::new()
20    }
21}
22
23impl<T> AllocVec<T> {
24    /// Creates a new empty [`AllocVec`] instance.
25    pub fn new() -> Self {
26        Self { vec: Vec::new() }
27    }
28
29    /// Creates a new [`AllocVec`] with the given capacity.
30    pub fn with_capacity(capacity: usize) -> Self {
31        Self {
32            vec: Vec::with_capacity(capacity),
33        }
34    }
35}
36
37impl<T> DerefMut for AllocVec<T> {
38    fn deref_mut(&mut self) -> &mut Self::Target {
39        &mut self.vec[..]
40    }
41}
42
43impl<T> Deref for AllocVec<T> {
44    type Target = [T];
45
46    fn deref(&self) -> &Self::Target {
47        &self.vec[..]
48    }
49}
50
51impl<T> Vector<T> for AllocVec<T> {
52    type Error = Infallible;
53
54    fn reserve(&mut self, additional: usize) -> Result<(), Self::Error> {
55        self.vec.reserve_exact(additional);
56        Ok(())
57    }
58
59    fn capacity(&self) -> usize {
60        self.vec.capacity()
61    }
62
63    fn push(&mut self, item: T) -> Result<(), Self::Error> {
64        self.vec.push(item);
65        Ok(())
66    }
67
68    fn clear(&mut self) {
69        self.vec.clear()
70    }
71}