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
//! Module providing a vector implementation based on [`alloc::vec::Vec`].

extern crate alloc;

use crate::vector::Vector;
use alloc::vec::Vec;
use core::{
    convert::Infallible,
    ops::{Deref, DerefMut},
};

/// Implements [`Vector`] with [`alloc::vec::Vec`].
pub struct AllocVec<T> {
    vec: Vec<T>,
}

impl<T> Default for AllocVec<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> AllocVec<T> {
    /// Creates a new empty [`AllocVec`] instance.
    pub fn new() -> Self {
        Self { vec: Vec::new() }
    }

    /// Creates a new [`AllocVec`] with the given capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            vec: Vec::with_capacity(capacity),
        }
    }
}

impl<T> DerefMut for AllocVec<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.vec[..]
    }
}

impl<T> Deref for AllocVec<T> {
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        &self.vec[..]
    }
}

impl<T> Vector<T> for AllocVec<T> {
    type Error = Infallible;

    fn reserve(&mut self, additional: usize) -> Result<(), Self::Error> {
        self.vec.reserve_exact(additional);
        Ok(())
    }

    fn capacity(&self) -> usize {
        self.vec.capacity()
    }

    fn push(&mut self, item: T) -> Result<(), Self::Error> {
        self.vec.push(item);
        Ok(())
    }

    fn clear(&mut self) {
        self.vec.clear()
    }
}