Debian Codegraph @

third_party/rust/naga/src/arena/handlevec.rs

raw
1 //! The [`HandleVec`] type and associated definitions.
2
3 use super::handle::Handle;
4 use alloc::{vec, vec::Vec};
5
6 use core::marker::PhantomData;
7 use core::ops;
8
9 /// A [`Vec`] indexed by [`Handle`]s.
10 ///
11 /// A `HandleVec<T, U>` is a [`Vec<U>`] indexed by values of type `Handle<T>`,
12 /// rather than `usize`.
13 ///
14 /// Rather than a `push` method, `HandleVec` has an [`insert`] method, analogous
15 /// to [`HashMap::insert`], that requires you to provide the handle at which the
16 /// new value should appear. However, since `HandleVec` only supports insertion
17 /// at the end, the given handle's index must be equal to the the `HandleVec`'s
18 /// current length; otherwise, the insertion will panic.
19 ///
20 /// [`insert`]: HandleVec::insert
21 /// [`HashMap::insert`]: hashbrown::HashMap::insert
22 #[derive(Debug)]
23 pub(crate) struct HandleVec<T, U> {
24 inner: Vec<U>,
25 as_keys: PhantomData<T>,
26 }
27
28 impl<T, U> Default for HandleVec<T, U> {
29 fn default() -> Self {
30 Self {
31 inner: vec![],
32 as_keys: PhantomData,
33 }
34 }
35 }
36
37 #[allow(dead_code)]
38 impl<T, U> HandleVec<T, U> {
39 pub(crate) const fn new() -> Self {
40 Self {
41 inner: vec![],
42 as_keys: PhantomData,
43 }
44 }
45
46 pub(crate) fn with_capacity(capacity: usize) -> Self {
47 Self {
48 inner: Vec::with_capacity(capacity),
49 as_keys: PhantomData,
50 }
51 }
52
53 pub(crate) fn len(&self) -> usize {
54 self.inner.len()
55 }
56
57 /// Insert a mapping from `handle` to `value`.
58 ///
59 /// Unlike a [`HashMap`], a `HandleVec` can only have new entries inserted at
60 /// the end, like [`Vec::push`]. So the index of `handle` must equal
61 /// [`self.len()`].
62 ///
63 /// [`HashMap`]: hashbrown::HashMap
64 /// [`self.len()`]: HandleVec::len
65 pub(crate) fn insert(&mut self, handle: Handle<T>, value: U) {
66 assert_eq!(handle.index(), self.inner.len());
67 self.inner.push(value);
68 }
69
70 pub(crate) fn get(&self, handle: Handle<T>) -> Option<&U> {
71 self.inner.get(handle.index())
72 }
73
74 pub(crate) fn clear(&mut self) {
75 self.inner.clear()
76 }
77
78 pub(crate) fn resize(&mut self, len: usize, fill: U)
79 where
80 U: Clone,
81 {
82 self.inner.resize(len, fill);
83 }
84
85 pub(crate) fn iter(&self) -> impl Iterator<Item = &U> {
86 self.inner.iter()
87 }
88
89 pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = &mut U> {
90 self.inner.iter_mut()
91 }
92 }
93
94 impl<T, U> ops::Index<Handle<T>> for HandleVec<T, U> {
95 type Output = U;
96
97 fn index(&self, handle: Handle<T>) -> &Self::Output {
98 &self.inner[handle.index()]
99 }
100 }
101
102 impl<T, U> ops::IndexMut<Handle<T>> for HandleVec<T, U> {
103 fn index_mut(&mut self, handle: Handle<T>) -> &mut Self::Output {
104 &mut self.inner[handle.index()]
105 }
106 }