Skip to main content

flow_span/index/
vec.rs

1//! A `Vec` whose positions are named by a typed index.
2
3use std::fmt;
4use std::marker::PhantomData;
5use std::ops::{Index, IndexMut};
6
7use super::idx::Idx;
8
9/// A vector keyed by `I` instead of by `usize`.
10///
11/// The whole point is [`push`](IndexVec::push): it appends and returns the
12/// index it assigned, so a producer names a node at the moment it creates one
13/// and never recomputes that name. Indexing panics on an out-of-range index the
14/// way `Vec` does, because an index of the wrong domain cannot be constructed
15/// in the first place and an index of the right domain that is out of range is
16/// a defect in the producer.
17///
18/// `PhantomData<fn(I)>` keeps `I` out of drop-checking and out of auto-trait
19/// inference: an `IndexVec<I, T>` is `Send`/`Sync` exactly when `T` is.
20pub struct IndexVec<I: Idx, T> {
21    raw: Vec<T>,
22    key: PhantomData<fn(I)>,
23}
24
25impl<I: Idx, T> IndexVec<I, T> {
26    /// Returns an empty vector.
27    pub const fn new() -> Self {
28        Self {
29            raw: Vec::new(),
30            key: PhantomData,
31        }
32    }
33
34    /// Returns an empty vector with room for `capacity` elements.
35    pub fn with_capacity(capacity: usize) -> Self {
36        Self {
37            raw: Vec::with_capacity(capacity),
38            key: PhantomData,
39        }
40    }
41
42    /// Adopts `raw`, naming its positions with `I`.
43    pub const fn from_raw(raw: Vec<T>) -> Self {
44        Self {
45            raw,
46            key: PhantomData,
47        }
48    }
49
50    /// Returns the underlying storage.
51    pub fn into_raw(self) -> Vec<T> {
52        self.raw
53    }
54
55    /// Appends `value` and returns the index it was assigned.
56    pub fn push(&mut self, value: T) -> I {
57        let index = self.next_index();
58        self.raw.push(value);
59        index
60    }
61
62    /// Removes and returns the last element.
63    pub fn pop(&mut self) -> Option<T> {
64        self.raw.pop()
65    }
66
67    /// Returns the index the next [`push`](IndexVec::push) will assign.
68    pub fn next_index(&self) -> I {
69        I::from_usize(self.raw.len())
70    }
71
72    /// Returns the number of elements.
73    pub fn len(&self) -> usize {
74        self.raw.len()
75    }
76
77    /// Returns whether there are no elements.
78    pub fn is_empty(&self) -> bool {
79        self.raw.is_empty()
80    }
81
82    /// Returns the element `index` names, or `None` when it is out of range.
83    pub fn get(&self, index: I) -> Option<&T> {
84        self.raw.get(index.index())
85    }
86
87    /// Returns the element `index` names mutably, or `None` when it is out of
88    /// range.
89    pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
90        self.raw.get_mut(index.index())
91    }
92
93    /// Returns the elements in position order.
94    pub fn iter(&self) -> std::slice::Iter<'_, T> {
95        self.raw.iter()
96    }
97
98    /// Returns the elements in position order, mutably.
99    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
100        self.raw.iter_mut()
101    }
102
103    /// Returns each element paired with the index naming it.
104    pub fn iter_enumerated(&self) -> impl DoubleEndedIterator<Item = (I, &T)> + ExactSizeIterator {
105        self.raw
106            .iter()
107            .enumerate()
108            .map(|(position, value)| (I::from_usize(position), value))
109    }
110
111    /// Returns each element paired with the index naming it, mutably.
112    pub fn iter_enumerated_mut(
113        &mut self,
114    ) -> impl DoubleEndedIterator<Item = (I, &mut T)> + ExactSizeIterator {
115        self.raw
116            .iter_mut()
117            .enumerate()
118            .map(|(position, value)| (I::from_usize(position), value))
119    }
120
121    /// Returns every index this vector currently names.
122    pub fn indices(&self) -> impl DoubleEndedIterator<Item = I> + ExactSizeIterator {
123        (0..self.raw.len()).map(I::from_usize)
124    }
125
126    /// Returns the elements as a plain slice.
127    pub fn as_slice(&self) -> &[T] {
128        &self.raw
129    }
130
131    /// Returns the elements as a plain mutable slice.
132    pub fn as_mut_slice(&mut self) -> &mut [T] {
133        &mut self.raw
134    }
135
136    /// Shortens the vector to `len` elements, dropping the rest.
137    pub fn truncate(&mut self, len: usize) {
138        self.raw.truncate(len);
139    }
140
141    /// Drops every element.
142    pub fn clear(&mut self) {
143        self.raw.clear();
144    }
145}
146
147impl<I: Idx, T: Clone> IndexVec<I, T> {
148    /// Returns a vector of `count` clones of `value`.
149    pub fn from_elem_n(value: T, count: usize) -> Self {
150        Self::from_raw(vec![value; count])
151    }
152
153    /// Grows the vector to `len` elements by cloning `value`.
154    pub fn resize(&mut self, len: usize, value: T) {
155        self.raw.resize(len, value);
156    }
157}
158
159impl<I: Idx, T> Default for IndexVec<I, T> {
160    fn default() -> Self {
161        Self::new()
162    }
163}
164
165impl<I: Idx, T> Index<I> for IndexVec<I, T> {
166    type Output = T;
167
168    fn index(&self, index: I) -> &T {
169        &self.raw[index.index()]
170    }
171}
172
173impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
174    fn index_mut(&mut self, index: I) -> &mut T {
175        &mut self.raw[index.index()]
176    }
177}
178
179impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
180    fn from_iter<It: IntoIterator<Item = T>>(iter: It) -> Self {
181        Self::from_raw(iter.into_iter().collect())
182    }
183}
184
185impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
186    type Item = T;
187    type IntoIter = std::vec::IntoIter<T>;
188
189    fn into_iter(self) -> Self::IntoIter {
190        self.raw.into_iter()
191    }
192}
193
194impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
195    type Item = &'a T;
196    type IntoIter = std::slice::Iter<'a, T>;
197
198    fn into_iter(self) -> Self::IntoIter {
199        self.raw.iter()
200    }
201}
202
203impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
204    type Item = &'a mut T;
205    type IntoIter = std::slice::IterMut<'a, T>;
206
207    fn into_iter(self) -> Self::IntoIter {
208        self.raw.iter_mut()
209    }
210}
211
212impl<I: Idx, T: Clone> Clone for IndexVec<I, T> {
213    fn clone(&self) -> Self {
214        Self::from_raw(self.raw.clone())
215    }
216}
217
218impl<I: Idx, T: PartialEq> PartialEq for IndexVec<I, T> {
219    fn eq(&self, other: &Self) -> bool {
220        self.raw == other.raw
221    }
222}
223
224impl<I: Idx, T: Eq> Eq for IndexVec<I, T> {}
225
226impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        f.debug_list().entries(&self.raw).finish()
229    }
230}
231
232#[cfg(test)]
233#[cfg_attr(coverage, coverage(off))]
234mod tests {
235    use super::IndexVec;
236
237    use super::super::test_index::{Node, node};
238
239    fn sample() -> IndexVec<Node, &'static str> {
240        IndexVec::from_raw(vec!["a", "b", "c"])
241    }
242
243    #[test]
244    fn push_returns_the_index_it_assigned() {
245        let mut nodes = IndexVec::<Node, u8>::new();
246        assert_eq!(nodes.next_index(), node(0));
247
248        let first = nodes.push(10);
249        let second = nodes.push(20);
250
251        assert_eq!(first, node(0));
252        assert_eq!(second, node(1));
253        assert_eq!(nodes[first], 10);
254        assert_eq!(nodes[second], 20);
255        assert_eq!(nodes.next_index(), node(2));
256        assert_eq!(nodes.len(), 2);
257        assert!(!nodes.is_empty());
258    }
259
260    #[test]
261    fn an_empty_vector_reports_itself_empty() {
262        let empty = IndexVec::<Node, u8>::default();
263        assert!(empty.is_empty());
264        assert_eq!(empty.len(), 0);
265        assert_eq!(empty.indices().count(), 0);
266
267        let with_room = IndexVec::<Node, u8>::with_capacity(8);
268        assert!(with_room.is_empty());
269        assert_eq!(with_room.len(), 0);
270        assert!(with_room.into_raw().capacity() >= 8);
271    }
272
273    #[test]
274    fn indexing_reads_and_writes_the_named_position() {
275        let mut nodes = sample();
276        assert_eq!(nodes[node(1)], "b");
277
278        nodes[node(1)] = "B";
279        assert_eq!(nodes[node(1)], "B");
280
281        *nodes.get_mut(node(2)).expect("in range") = "C";
282        assert_eq!(nodes.get(node(2)), Some(&"C"));
283    }
284
285    #[test]
286    fn an_out_of_range_index_reads_as_absent() {
287        let mut nodes = sample();
288        assert_eq!(nodes.get(node(3)), None);
289        assert_eq!(nodes.get_mut(node(3)), None);
290    }
291
292    #[test]
293    #[should_panic(expected = "index out of bounds")]
294    fn indexing_past_the_end_is_a_defect() {
295        let _ = sample()[node(3)];
296    }
297
298    #[test]
299    #[should_panic(expected = "index out of bounds")]
300    fn indexing_past_the_end_mutably_is_a_defect() {
301        let mut nodes = sample();
302        nodes[node(3)] = "d";
303    }
304
305    #[test]
306    fn iteration_walks_positions_in_order() {
307        let mut nodes = sample();
308
309        assert_eq!(nodes.iter().copied().collect::<Vec<_>>(), ["a", "b", "c"]);
310        assert_eq!(
311            nodes
312                .iter_enumerated()
313                .map(|(index, value)| (index, *value))
314                .collect::<Vec<_>>(),
315            [(node(0), "a"), (node(1), "b"), (node(2), "c"),],
316        );
317        assert_eq!(
318            nodes.indices().collect::<Vec<_>>(),
319            [node(0), node(1), node(2)],
320        );
321
322        nodes.iter_mut().for_each(|value| *value = "x");
323        assert_eq!(nodes.as_slice(), ["x", "x", "x"]);
324
325        for (index, value) in nodes.iter_enumerated_mut() {
326            if index == node(0) {
327                *value = "y";
328            }
329        }
330        assert_eq!(nodes.as_slice(), ["y", "x", "x"]);
331        assert_eq!(nodes.as_mut_slice().len(), 3);
332    }
333
334    #[test]
335    fn iteration_is_double_ended_and_sized() {
336        let nodes = sample();
337        assert_eq!(nodes.iter_enumerated().len(), 3);
338        assert_eq!(
339            nodes.iter_enumerated().next_back().map(|(_, v)| *v),
340            Some("c")
341        );
342        assert_eq!(nodes.indices().len(), 3);
343        assert_eq!(nodes.indices().next_back(), Some(node(2)));
344
345        let mut nodes = sample();
346        assert_eq!(nodes.iter_enumerated_mut().len(), 3);
347        assert_eq!(
348            nodes.iter_enumerated_mut().next_back().map(|(_, v)| *v),
349            Some("c")
350        );
351    }
352
353    #[test]
354    fn a_vector_converts_to_and_from_plain_storage() {
355        let nodes: IndexVec<Node, u8> = [1_u8, 2, 3].into_iter().collect();
356        assert_eq!(nodes.clone().into_raw(), vec![1, 2, 3]);
357        assert_eq!(nodes.into_iter().collect::<Vec<_>>(), vec![1, 2, 3]);
358    }
359
360    #[test]
361    fn borrowed_iteration_reaches_both_reference_forms() {
362        let mut nodes = sample();
363        assert_eq!((&nodes).into_iter().count(), 3);
364
365        let lengths: Vec<usize> = (&mut nodes).into_iter().map(|value| value.len()).collect();
366        assert_eq!(lengths, [1, 1, 1]);
367    }
368
369    #[test]
370    fn cloning_repeats_a_value_and_resizing_extends_it() {
371        let mut nodes = IndexVec::<Node, u8>::from_elem_n(7, 2);
372        assert_eq!(nodes.as_slice(), [7, 7]);
373
374        nodes.resize(4, 9);
375        assert_eq!(nodes.as_slice(), [7, 7, 9, 9]);
376    }
377
378    #[test]
379    fn shortening_drops_the_tail() {
380        let mut nodes = sample();
381        assert_eq!(nodes.pop(), Some("c"));
382
383        nodes.truncate(1);
384        assert_eq!(nodes.as_slice(), ["a"]);
385
386        nodes.clear();
387        assert!(nodes.is_empty());
388        assert_eq!(nodes.pop(), None);
389    }
390
391    #[test]
392    fn equality_and_debug_read_through_to_the_elements() {
393        assert_eq!(sample(), sample());
394        assert_ne!(sample(), IndexVec::<Node, &str>::new());
395        assert_eq!(format!("{:?}", sample()), r#"["a", "b", "c"]"#);
396    }
397}