charon_lib/ids/
vector.rs

1//! A vector with custom index types.
2//!
3//! This data-structure is mostly meant to be used with the index types defined
4//! with [`crate::generate_index_type!`]: by using custom index types, we
5//! leverage the type checker to prevent us from mixing them.
6//!
7//! Note that this data structure is implemented by using persistent vectors.
8//! This makes the clone operation almost a no-op.
9
10use index_vec::{Idx, IdxSliceIndex, IndexVec};
11use serde::{Deserialize, Serialize, Serializer};
12use std::{
13    iter::{FromIterator, IntoIterator},
14    mem,
15    ops::{ControlFlow, Deref, Index, IndexMut},
16};
17
18use derive_generic_visitor::*;
19
20/// Indexed vector.
21/// To prevent accidental id reuse, the vector supports reserving a slot to be filled later.
22#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub struct Vector<I, T>
24where
25    I: Idx,
26{
27    vector: IndexVec<I, Option<T>>,
28    /// The number of non-`None` elements.
29    elem_count: usize,
30}
31
32impl<I: std::fmt::Debug, T: std::fmt::Debug> std::fmt::Debug for Vector<I, T>
33where
34    I: Idx,
35{
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        <IndexVec<_, _> as std::fmt::Debug>::fmt(&self.vector, f)
38    }
39}
40
41pub struct ReservedSlot<I: Idx>(I);
42
43impl<I, T> Vector<I, T>
44where
45    I: Idx,
46{
47    pub fn new() -> Self {
48        Vector {
49            vector: IndexVec::new(),
50            elem_count: 0,
51        }
52    }
53
54    pub fn with_capacity(capacity: usize) -> Self {
55        Vector {
56            vector: IndexVec::with_capacity(capacity),
57            elem_count: 0,
58        }
59    }
60
61    pub fn get(&self, i: I) -> Option<&T> {
62        self.vector.get(i).map(Option::as_ref).flatten()
63    }
64
65    pub fn get_mut(&mut self, i: I) -> Option<&mut T> {
66        self.vector.get_mut(i).map(Option::as_mut).flatten()
67    }
68
69    pub fn is_empty(&self) -> bool {
70        self.elem_count == 0
71    }
72
73    /// The number of elements stored in the vector.
74    pub fn elem_count(&self) -> usize {
75        self.elem_count
76    }
77
78    /// The number of slots allocated in the vector (empty or not).
79    pub fn slot_count(&self) -> usize {
80        self.vector.len()
81    }
82
83    /// Gets the value of the next available id. Avoid if possible; use `reserve_slot` instead.
84    pub fn next_id(&self) -> I {
85        self.vector.next_idx()
86    }
87
88    /// Reserve a spot in the vector.
89    pub fn reserve_slot(&mut self) -> I {
90        // Push a `None` to ensure we don't reuse the id.
91        self.vector.push(None)
92    }
93
94    /// Fill the reserved slot.
95    pub fn set_slot(&mut self, id: I, x: T) {
96        assert!(self.vector[id].is_none());
97        self.vector[id] = Some(x);
98        self.elem_count += 1;
99    }
100
101    /// Remove the value from this slot, leaving other ids unchanged.
102    pub fn remove(&mut self, id: I) -> Option<T> {
103        if self.vector[id].is_some() {
104            self.elem_count -= 1;
105        }
106        self.vector[id].take()
107    }
108
109    /// Remove the value from this slot, shifting other ids as needed.
110    pub fn remove_and_shift_ids(&mut self, id: I) -> Option<T> {
111        if self.vector[id].is_some() {
112            self.elem_count -= 1;
113        }
114        self.vector.remove(id)
115    }
116
117    pub fn push(&mut self, x: T) -> I {
118        self.elem_count += 1;
119        self.vector.push(Some(x))
120    }
121
122    pub fn push_with(&mut self, f: impl FnOnce(I) -> T) -> I {
123        let id = self.reserve_slot();
124        let x = f(id);
125        self.set_slot(id, x);
126        id
127    }
128
129    pub fn push_all<It>(&mut self, it: It) -> impl Iterator<Item = I> + use<'_, I, T, It>
130    where
131        It: Iterator<Item = T>,
132    {
133        it.map(move |x| self.push(x))
134    }
135
136    pub fn extend<It>(&mut self, it: It)
137    where
138        It: Iterator<Item = T>,
139    {
140        self.push_all(it).for_each(|_| ())
141    }
142
143    pub fn extend_from_slice(&mut self, other: &Self)
144    where
145        T: Clone,
146    {
147        self.vector.extend_from_slice(&other.vector);
148        self.elem_count += other.elem_count;
149    }
150
151    /// Insert a value at that index, shifting all the values with equal or larger indices.
152    pub fn insert_and_shift_ids(&mut self, id: I, x: T) {
153        self.elem_count += 1;
154        self.vector.insert(id, Some(x))
155    }
156
157    /// Get a mutable reference into the ith element. If the vector is too short, extend it until
158    /// it has enough elements. If the element doesn't exist, use the provided function to
159    /// initialize it.
160    pub fn get_or_extend_and_insert(&mut self, id: I, f: impl FnOnce() -> T) -> &mut T {
161        if id.index() >= self.vector.len() {
162            self.vector.resize_with(id.index() + 1, || None);
163        }
164        self.vector[id].get_or_insert_with(f)
165    }
166
167    /// Map each entry to a new one, keeping the same ids.
168    pub fn map<U>(self, mut f: impl FnMut(T) -> U) -> Vector<I, U> {
169        Vector {
170            vector: self
171                .vector
172                .into_iter()
173                .map(|x_opt| x_opt.map(&mut f))
174                .collect(),
175            elem_count: self.elem_count,
176        }
177    }
178
179    /// Map each entry to a new one, keeping the same ids.
180    pub fn map_ref<'a, U>(&'a self, mut f: impl FnMut(&'a T) -> U) -> Vector<I, U> {
181        Vector {
182            vector: self
183                .vector
184                .iter()
185                .map(|x_opt| x_opt.as_ref().map(&mut f))
186                .collect(),
187            elem_count: self.elem_count,
188        }
189    }
190
191    /// Map each entry to a new one, keeping the same ids.
192    pub fn map_ref_mut<'a, U>(&'a mut self, mut f: impl FnMut(&'a mut T) -> U) -> Vector<I, U> {
193        Vector {
194            vector: self
195                .vector
196                .iter_mut()
197                .map(|x_opt| x_opt.as_mut().map(&mut f))
198                .collect(),
199            elem_count: self.elem_count,
200        }
201    }
202
203    /// Map each entry to a new one, keeping the same ids.
204    pub fn map_ref_indexed<'a, U>(&'a self, mut f: impl FnMut(I, &'a T) -> U) -> Vector<I, U> {
205        Vector {
206            vector: self
207                .vector
208                .iter_enumerated()
209                .map(|(i, x_opt)| x_opt.as_ref().map(|x| f(i, x)))
210                .collect(),
211            elem_count: self.elem_count,
212        }
213    }
214
215    /// Map each entry to a new one, keeping the same ids. Includes empty slots.
216    pub fn map_opt<U>(self, f: impl FnMut(Option<T>) -> Option<U>) -> Vector<I, U> {
217        Vector {
218            vector: self.vector.into_iter().map(f).collect(),
219            elem_count: self.elem_count,
220        }
221    }
222
223    /// Map each entry to a new one, keeping the same ids. Includes empty slots.
224    pub fn map_ref_opt<'a, U>(
225        &'a self,
226        mut f: impl FnMut(Option<&'a T>) -> Option<U>,
227    ) -> Vector<I, U> {
228        let mut ret = Vector {
229            vector: self.vector.iter().map(|x_opt| f(x_opt.as_ref())).collect(),
230            elem_count: self.elem_count,
231        };
232        ret.elem_count = ret.iter().count();
233        ret
234    }
235
236    /// Iter over the nonempty slots.
237    pub fn iter(&self) -> impl Iterator<Item = &T> + DoubleEndedIterator + Clone {
238        self.vector.iter().filter_map(|opt| opt.as_ref())
239    }
240
241    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> + DoubleEndedIterator {
242        self.vector.iter_mut().filter_map(|opt| opt.as_mut())
243    }
244
245    pub fn iter_indexed(&self) -> impl Iterator<Item = (I, &T)> {
246        self.vector
247            .iter_enumerated()
248            .flat_map(|(i, opt)| Some((i, opt.as_ref()?)))
249    }
250
251    pub fn iter_mut_indexed(&mut self) -> impl Iterator<Item = (I, &mut T)> {
252        self.vector
253            .iter_mut_enumerated()
254            .flat_map(|(i, opt)| Some((i, opt.as_mut()?)))
255    }
256
257    pub fn into_iter_indexed(self) -> impl Iterator<Item = (I, T)> {
258        self.vector
259            .into_iter_enumerated()
260            .flat_map(|(i, opt)| Some((i, opt?)))
261    }
262
263    pub fn iter_indexed_values(&self) -> impl Iterator<Item = (I, &T)> {
264        self.iter_indexed()
265    }
266
267    pub fn into_iter_indexed_values(self) -> impl Iterator<Item = (I, T)> {
268        self.into_iter_indexed()
269    }
270
271    /// Iterate over all slots, even empty ones.
272    pub fn iter_all_slots(&self) -> impl Iterator<Item = &Option<T>> {
273        self.vector.iter()
274    }
275
276    pub fn iter_indexed_all_slots(&self) -> impl Iterator<Item = (I, &Option<T>)> {
277        self.vector.iter_enumerated()
278    }
279
280    pub fn iter_indices(&self) -> impl Iterator<Item = I> + '_ {
281        // Reuse `iter_indexed` to filter only the filled indices.
282        self.iter_indexed().map(|(id, _)| id)
283    }
284
285    pub fn all_indices(&self) -> impl Iterator<Item = I> {
286        self.vector.indices()
287    }
288
289    /// Remove matching items and return and iterator over the removed items. This is lazy: items
290    /// are only removed as the iterator is consumed.
291    pub fn extract<'a, F: FnMut(&mut T) -> bool>(
292        &'a mut self,
293        mut f: F,
294    ) -> impl Iterator<Item = (I, T)> + use<'a, I, T, F> {
295        let elem_count = &mut self.elem_count;
296        self.vector
297            .iter_mut_enumerated()
298            .filter_map(move |(i, opt)| {
299                if f(opt.as_mut()?) {
300                    *elem_count -= 1;
301                    let elem = mem::replace(opt, None)?;
302                    Some((i, elem))
303                } else {
304                    None
305                }
306            })
307    }
308
309    /// Remove the elements that don't match the predicate.
310    pub fn retain(&mut self, mut f: impl FnMut(&mut T) -> bool) {
311        self.extract(|x| !f(x)).for_each(drop);
312    }
313
314    /// Like `Vec::split_off`.
315    pub fn split_off(&mut self, at: usize) -> Self {
316        let mut ret = Self {
317            vector: self.vector.split_off(I::from_usize(at)),
318            elem_count: 0,
319        };
320        self.elem_count = self.iter().count();
321        ret.elem_count = ret.iter().count();
322        ret
323    }
324}
325
326impl<I: Idx, T> Default for Vector<I, T> {
327    fn default() -> Self {
328        Self::new()
329    }
330}
331
332impl<I: Idx> Deref for ReservedSlot<I> {
333    type Target = I;
334    fn deref(&self) -> &Self::Target {
335        &self.0
336    }
337}
338
339impl<I, R, T> Index<R> for Vector<I, T>
340where
341    I: Idx,
342    R: IdxSliceIndex<I, Option<T>, Output = Option<T>>,
343{
344    type Output = T;
345    fn index(&self, index: R) -> &Self::Output {
346        self.vector[index].as_ref().unwrap()
347    }
348}
349
350impl<I, R, T> IndexMut<R> for Vector<I, T>
351where
352    I: Idx,
353    R: IdxSliceIndex<I, Option<T>, Output = Option<T>>,
354{
355    fn index_mut(&mut self, index: R) -> &mut Self::Output {
356        self.vector[index].as_mut().unwrap()
357    }
358}
359
360impl<'a, I, T> IntoIterator for &'a Vector<I, T>
361where
362    I: Idx,
363{
364    type Item = &'a T;
365    type IntoIter = impl Iterator<Item = &'a T>;
366
367    fn into_iter(self) -> Self::IntoIter {
368        self.vector.iter().flat_map(|opt| opt.as_ref())
369    }
370}
371
372impl<'a, I, T> IntoIterator for &'a mut Vector<I, T>
373where
374    I: Idx,
375{
376    type Item = &'a mut T;
377    type IntoIter = impl Iterator<Item = &'a mut T>;
378
379    fn into_iter(self) -> Self::IntoIter {
380        self.vector.iter_mut().flat_map(|opt| opt.as_mut())
381    }
382}
383
384impl<I, T> IntoIterator for Vector<I, T>
385where
386    I: Idx,
387{
388    type Item = T;
389    type IntoIter = impl Iterator<Item = T>;
390
391    fn into_iter(self) -> Self::IntoIter {
392        self.vector.into_iter().flat_map(|opt| opt)
393    }
394}
395
396// FIXME: this impl is a footgun
397impl<I, T> FromIterator<T> for Vector<I, T>
398where
399    I: Idx,
400{
401    #[inline]
402    fn from_iter<It: IntoIterator<Item = T>>(iter: It) -> Vector<I, T> {
403        let mut elem_count = 0;
404        let vector = IndexVec::from_iter(iter.into_iter().inspect(|_| elem_count += 1).map(Some));
405        Vector { vector, elem_count }
406    }
407}
408
409// FIXME: this impl is a footgun
410impl<I, T> From<Vec<T>> for Vector<I, T>
411where
412    I: Idx,
413{
414    fn from(v: Vec<T>) -> Self {
415        v.into_iter().collect()
416    }
417}
418
419// FIXME: this impl is a footgun
420impl<I, T, const N: usize> From<[T; N]> for Vector<I, T>
421where
422    I: Idx,
423{
424    fn from(v: [T; N]) -> Self {
425        v.into_iter().collect()
426    }
427}
428
429impl<I: Idx, T: Serialize> Serialize for Vector<I, T> {
430    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
431    where
432        S: Serializer,
433    {
434        self.vector.serialize(serializer)
435    }
436}
437
438impl<'de, I: Idx, T: Deserialize<'de>> Deserialize<'de> for Vector<I, T> {
439    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
440    where
441        D: serde::Deserializer<'de>,
442    {
443        let mut ret = Self {
444            vector: Deserialize::deserialize(deserializer)?,
445            elem_count: 0,
446        };
447        ret.elem_count = ret.iter().count();
448        Ok(ret)
449    }
450}
451
452impl<'s, I: Idx, T, V: Visit<'s, T>> Drive<'s, V> for Vector<I, T> {
453    fn drive_inner(&'s self, v: &mut V) -> ControlFlow<V::Break> {
454        for x in self {
455            v.visit(x)?;
456        }
457        Continue(())
458    }
459}
460impl<'s, I: Idx, T, V: VisitMut<'s, T>> DriveMut<'s, V> for Vector<I, T> {
461    fn drive_inner_mut(&'s mut self, v: &mut V) -> ControlFlow<V::Break> {
462        for x in self {
463            v.visit(x)?;
464        }
465        Continue(())
466    }
467}