tagged_vec/
lib.rs

1//! An alternative to the standard libraries' [`Vec`] which is indexed with a custom type instead of [`usize`].
2//!
3//! This is useful to catch errors like using the wrong variable to index the vector.
4
5#![warn(missing_docs)]
6
7use std::{marker::PhantomData, ops::RangeBounds};
8
9use mapped_range_bounds::MappedRangeBounds;
10
11mod mapped_range_bounds;
12mod trait_impls;
13
14/// A [`Vec`] wrapper that allows indexing only via the given `Index` type.
15///
16/// For actual operation, `Index` must implement [`From<usize>`] and [`Into<usize>`].
17pub struct TaggedVec<Index, Value> {
18    index_type: PhantomData<Index>,
19    vec: Vec<Value>,
20}
21
22impl<Index, Value> TaggedVec<Index, Value> {
23    /// Creates a new empty `TaggedVec`.
24    pub fn new() -> Self {
25        Self::default()
26    }
27
28    /// Returns the number of elements in the `TaggedVec`.
29    pub fn len(&self) -> usize {
30        self.vec.len()
31    }
32
33    /// Returns `true` if the `TaggedVec` contains no elements.
34    pub fn is_empty(&self) -> bool {
35        self.vec.is_empty()
36    }
37
38    /// Inserts the given value at the back of the `TaggedVec`, returning its index.
39    pub fn push(&mut self, value: Value) -> Index
40    where
41        Index: From<usize>,
42    {
43        let index = self.vec.len().into();
44        self.vec.push(value);
45        index
46    }
47
48    /// Removes the value at the back of the `TaggedVec` and returns it with its index.
49    pub fn pop(&mut self) -> Option<(Index, Value)>
50    where
51        Index: From<usize>,
52    {
53        if let Some(value) = self.vec.pop() {
54            Some((self.vec.len().into(), value))
55        } else {
56            None
57        }
58    }
59
60    /// Inserts the given `value` at position `index`, shifting all existing values in range `index..` one position to the right.
61    pub fn insert(&mut self, index: Index, value: Value)
62    where
63        Index: Into<usize>,
64    {
65        self.vec.insert(index.into(), value);
66    }
67
68    /// See [`Vec::splice`].
69    pub fn splice<I: IntoIterator<Item = Value>>(
70        &mut self,
71        range: impl RangeBounds<Index>,
72        replace_with: I,
73    ) -> std::vec::Splice<'_, I::IntoIter>
74    where
75        usize: for<'a> From<&'a Index>,
76    {
77        self.vec.splice(MappedRangeBounds::new(range), replace_with)
78    }
79
80    /// Retains only the values specified by the predicate.
81    ///
82    /// In other words, remove all values `v` for which `f(&v)` returns `false`.
83    /// This method operates in place, visiting each value exactly once in the original order, and preserves the order of the retained values.
84    pub fn retain(&mut self, f: impl FnMut(&Value) -> bool) {
85        self.vec.retain(f);
86    }
87
88    /// Removes the elements at the specified indices, shifting other elements to the left to fill gaps as required.
89    ///
90    /// The provided indices must be sorted.
91    pub fn remove_multi(&mut self, indices: impl IntoIterator<Item = Index>)
92    where
93        Index: Into<usize> + Clone,
94    {
95        let mut indices = indices.into_iter().peekable();
96        let mut current_index = 0;
97        self.vec.retain(|_| {
98            if let Some(next_delete_index) = indices.peek() {
99                let next_delete_index = next_delete_index.clone().into();
100                let result = if next_delete_index == current_index {
101                    indices.next();
102
103                    if let Some(next_next_delete_index) = indices.peek() {
104                        let next_next_delete_index: usize = next_next_delete_index.clone().into();
105                        assert!(next_next_delete_index > next_delete_index);
106                    }
107
108                    false
109                } else {
110                    true
111                };
112                current_index += 1;
113                result
114            } else {
115                true
116            }
117        });
118
119        assert!(indices.next().is_none());
120    }
121
122    /// Returns an iterator over references to the entries of the `TaggedVec`.
123    pub fn iter(&self) -> impl Iterator<Item = (Index, &Value)>
124    where
125        Index: From<usize>,
126    {
127        self.vec
128            .iter()
129            .enumerate()
130            .map(|(index, value)| (index.into(), value))
131    }
132
133    /// Returns an iterator over mutable references to the entries of the `TaggedVec`.
134    pub fn iter_mut(&mut self) -> impl Iterator<Item = (Index, &mut Value)>
135    where
136        Index: From<usize>,
137    {
138        self.vec
139            .iter_mut()
140            .enumerate()
141            .map(|(index, value)| (index.into(), value))
142    }
143
144    /// Returns an iterator over references to the values of the `TaggedVec`.
145    pub fn iter_values(&self) -> std::slice::Iter<'_, Value> {
146        self.vec.iter()
147    }
148
149    /// Returns an iterator over mutable references to the values of the `TaggedVec`.
150    pub fn iter_values_mut(&mut self) -> std::slice::IterMut<'_, Value> {
151        self.vec.iter_mut()
152    }
153
154    /// Returns an iterator over the indices of the `TaggedVec`.
155    pub fn iter_indices(&self) -> impl Iterator<Item = Index>
156    where
157        Index: From<usize>,
158    {
159        (0..self.vec.len()).map(Into::into)
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use crate::TaggedVec;
166
167    #[test]
168    fn delete_multi() {
169        let mut v = TaggedVec::<usize, _>::from_iter([0, 1, 2, 3, 4]);
170        v.remove_multi([0, 4]);
171        assert_eq!(v, vec![1, 2, 3].into());
172
173        let mut v = TaggedVec::<usize, _>::from_iter([0, 1, 2, 3, 4]);
174        v.remove_multi([0, 2, 4]);
175        assert_eq!(v, vec![1, 3].into());
176
177        let mut v = TaggedVec::<usize, _>::from_iter([0, 1, 2, 3, 4]);
178        v.remove_multi([1, 3]);
179        assert_eq!(v, vec![0, 2, 4].into());
180    }
181}