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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//! Module providing abstractions for reperesenting vectors.

use core::ops::DerefMut;

/// Represents an abstract vector over a type accessible as mutable slice.
pub trait Vector<T>: DerefMut<Target = [T]> {
    type Error: core::fmt::Debug;

    /// Reserves memory for the given number of additional items in this vector.
    fn reserve(&mut self, additional: usize) -> Result<(), Self::Error>;

    /// Returns the number of items this vector is capable of storing.
    fn capacity(&self) -> usize;

    /// Pushes a new element to the end of this vector.
    fn push(&mut self, item: T) -> Result<(), Self::Error>;

    /// Removes all elements from this vector.
    fn clear(&mut self);
}

pub mod impls;

#[doc(hidden)]
pub mod tests {
    use super::Vector;

    pub fn _test_vector_consistency<V: Vector<usize>>(mut vector: V) {
        vector.clear();

        let cap_0 = vector.capacity();

        vector.reserve(vector.capacity()).unwrap();

        let cap_1 = vector.capacity();

        assert_eq!(cap_0, cap_1);

        assert!(vector.is_empty());

        for i in 0..vector.capacity() {
            vector.push(i).unwrap();
        }

        assert_eq!(vector.len(), vector.capacity());

        for (j, i) in vector.iter().enumerate() {
            assert_eq!(i, &j);
        }

        let cap_0 = vector.capacity();

        let res = vector.push(42);

        let cap_1 = vector.capacity();

        if cap_0 == cap_1 {
            assert!(res.is_err());
        } else {
            assert!(cap_1 > cap_0, "Capacity decreased on push().");
            assert!(res.is_ok());
        }

        let cap_0 = vector.capacity();

        vector.clear();

        let cap_1 = vector.capacity();

        assert!(cap_0 == cap_1, "Capacity changed on clear().");

        assert!(vector.is_empty());

        const ADDITIONAL: usize = 5;

        let result = vector.reserve(ADDITIONAL);

        if result.is_err() {
            return;
        }

        for i in 0..ADDITIONAL {
            vector.push(i).unwrap();
        }
    }
}