Skip to main content

prjcombine_entity/
vec.rs

1//! A vector with strongly-typed indices.
2
3use core::cmp::Ordering;
4use core::hash::Hash;
5use core::marker::PhantomData;
6use core::ops::{Index, IndexMut};
7use std::fmt;
8
9use crate::EntityId;
10use crate::id::EntityRange;
11
12/// A vector with strongly-typed indices.
13#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
14#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
15pub struct EntityVec<I: EntityId, V> {
16    vals: Vec<V>,
17    ids: PhantomData<I>,
18}
19
20impl<I: EntityId, V> EntityVec<I, V> {
21    /// Create a new, empty `EntityVec`.
22    pub fn new() -> Self {
23        Self {
24            vals: Vec::new(),
25            ids: PhantomData,
26        }
27    }
28
29    /// See [`Vec::with_capacity`].
30    pub fn with_capacity(cap: usize) -> Self {
31        Self {
32            vals: Vec::with_capacity(cap),
33            ids: PhantomData,
34        }
35    }
36
37    pub fn get(&self, idx: I) -> Option<&V> {
38        self.vals.get(idx.to_idx())
39    }
40
41    pub fn get_mut(&mut self, idx: I) -> Option<&mut V> {
42        self.vals.get_mut(idx.to_idx())
43    }
44
45    /// Obtains a reference to a given element of the vector, without checking index validity.
46    ///
47    /// # Safety
48    ///
49    /// The caller must ensure that `idx` is a valid index within this vector.
50    pub unsafe fn get_unchecked(&self, idx: I) -> &V {
51        unsafe { self.vals.get_unchecked(idx.to_idx()) }
52    }
53
54    /// Obtains a mutable reference to a given element of the vector, without checking index validity.
55    ///
56    /// # Safety
57    ///
58    /// The caller must ensure that `idx` is a valid index within this vector.
59    pub unsafe fn get_unchecked_mut(&mut self, idx: I) -> &mut V {
60        unsafe { self.vals.get_unchecked_mut(idx.to_idx()) }
61    }
62
63    /// Appends an element, returning its index.
64    pub fn push(&mut self, val: V) -> I {
65        let res = I::from_idx(self.vals.len());
66        self.vals.push(val);
67        res
68    }
69
70    pub fn len(&self) -> usize {
71        self.vals.len()
72    }
73
74    pub fn is_empty(&self) -> bool {
75        self.vals.is_empty()
76    }
77
78    pub fn clear(&mut self) {
79        self.vals.clear()
80    }
81
82    pub fn ids(&self) -> EntityRange<I> {
83        EntityRange::new(0, self.vals.len())
84    }
85
86    pub fn values(&self) -> core::slice::Iter<'_, V> {
87        self.vals.iter()
88    }
89
90    pub fn values_mut(&mut self) -> core::slice::IterMut<'_, V> {
91        self.vals.iter_mut()
92    }
93
94    pub fn into_values(self) -> std::vec::IntoIter<V> {
95        self.vals.into_iter()
96    }
97
98    // Returns iterator of pairs `(id, &value)`.
99    pub fn iter(&self) -> Iter<'_, I, V> {
100        Iter {
101            vals: self.vals.iter(),
102            pos: 0,
103            ids: PhantomData,
104        }
105    }
106
107    // Returns iterator of pairs `(id, &mut value)`.
108    pub fn iter_mut(&mut self) -> IterMut<'_, I, V> {
109        IterMut {
110            vals: self.vals.iter_mut(),
111            pos: 0,
112            ids: PhantomData,
113        }
114    }
115
116    pub fn map<'a, NV>(&'a self, mut f: impl FnMut(I, &'a V) -> NV) -> EntityVec<I, NV> {
117        self.iter().map(|(i, v)| f(i, v)).collect()
118    }
119
120    pub fn map_values<'a, NV>(&'a self, f: impl FnMut(&'a V) -> NV) -> EntityVec<I, NV> {
121        self.values().map(f).collect()
122    }
123
124    pub fn into_map_values<NV>(self, f: impl FnMut(V) -> NV) -> EntityVec<I, NV> {
125        self.into_values().map(f).collect()
126    }
127
128    pub fn first(&self) -> Option<&V> {
129        self.vals.first()
130    }
131
132    pub fn first_mut(&mut self) -> Option<&mut V> {
133        self.vals.first_mut()
134    }
135
136    pub fn first_id(&self) -> Option<I> {
137        self.ids().first()
138    }
139
140    pub fn last(&self) -> Option<&V> {
141        self.vals.last()
142    }
143
144    pub fn last_mut(&mut self) -> Option<&mut V> {
145        self.vals.last_mut()
146    }
147
148    pub fn last_id(&self) -> Option<I> {
149        self.ids().last()
150    }
151
152    pub fn next_id(&self) -> I {
153        self.ids().end()
154    }
155
156    /// See [`[T]::binary_search`].
157    pub fn binary_search(&self, x: &V) -> Result<I, I>
158    where
159        V: Ord,
160    {
161        match self.vals.binary_search(x) {
162            Ok(x) => Ok(I::from_idx(x)),
163            Err(x) => Err(I::from_idx(x)),
164        }
165    }
166
167    /// See [`[T]::binary_search_by`].
168    pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<I, I>
169    where
170        F: FnMut(&'a V) -> Ordering,
171    {
172        match self.vals.binary_search_by(f) {
173            Ok(x) => Ok(I::from_idx(x)),
174            Err(x) => Err(I::from_idx(x)),
175        }
176    }
177
178    /// See [`[T]::binary_search_by_key`].
179    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<I, I>
180    where
181        F: FnMut(&'a V) -> B,
182        B: Ord,
183    {
184        match self.vals.binary_search_by_key(b, f) {
185            Ok(x) => Ok(I::from_idx(x)),
186            Err(x) => Err(I::from_idx(x)),
187        }
188    }
189
190    pub fn pop(&mut self) -> Option<(I, V)> {
191        self.vals.pop().map(|x| (self.next_id(), x))
192    }
193}
194
195impl<I: EntityId, V> Default for EntityVec<I, V> {
196    fn default() -> Self {
197        Self::new()
198    }
199}
200
201impl<I, V> fmt::Debug for EntityVec<I, V>
202where
203    I: EntityId,
204    V: fmt::Debug,
205{
206    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
207        fmt.debug_map().entries(self).finish()
208    }
209}
210
211impl<I: EntityId, V> IntoIterator for EntityVec<I, V> {
212    type Item = (I, V);
213    type IntoIter = IntoIter<I, V>;
214    fn into_iter(self) -> Self::IntoIter {
215        IntoIter {
216            vals: self.vals.into_iter(),
217            pos: 0,
218            ids: PhantomData,
219        }
220    }
221}
222
223impl<'a, I: EntityId, V> IntoIterator for &'a EntityVec<I, V> {
224    type Item = (I, &'a V);
225    type IntoIter = Iter<'a, I, V>;
226    fn into_iter(self) -> Self::IntoIter {
227        self.iter()
228    }
229}
230
231impl<'a, I: EntityId, V> IntoIterator for &'a mut EntityVec<I, V> {
232    type Item = (I, &'a mut V);
233    type IntoIter = IterMut<'a, I, V>;
234    fn into_iter(self) -> Self::IntoIter {
235        self.iter_mut()
236    }
237}
238
239impl<I: EntityId, V> Index<I> for EntityVec<I, V> {
240    type Output = V;
241    fn index(&self, index: I) -> &V {
242        &self.vals[index.to_idx()]
243    }
244}
245
246impl<I: EntityId, V> IndexMut<I> for EntityVec<I, V> {
247    fn index_mut(&mut self, index: I) -> &mut V {
248        &mut self.vals[index.to_idx()]
249    }
250}
251
252/// Iterator of `(id, &value)` pairs.
253#[derive(Clone, Debug)]
254pub struct Iter<'a, I, V> {
255    vals: core::slice::Iter<'a, V>,
256    pos: usize,
257    ids: PhantomData<I>,
258}
259
260impl<'a, I: EntityId, V> Iterator for Iter<'a, I, V> {
261    type Item = (I, &'a V);
262    fn next(&mut self) -> Option<(I, &'a V)> {
263        let val = self.vals.next()?;
264        let id = I::from_idx(self.pos);
265        self.pos += 1;
266        Some((id, val))
267    }
268}
269
270impl<'a, I: EntityId, V> DoubleEndedIterator for Iter<'a, I, V> {
271    fn next_back(&mut self) -> Option<(I, &'a V)> {
272        let val = self.vals.next_back()?;
273        Some((I::from_idx(self.pos + self.vals.len()), val))
274    }
275}
276
277impl<'a, I: EntityId, V> ExactSizeIterator for Iter<'a, I, V> {
278    fn len(&self) -> usize {
279        self.vals.len()
280    }
281}
282
283/// Iterator of `(id, &mut value)` pairs.
284#[derive(Debug)]
285pub struct IterMut<'a, I, V> {
286    vals: core::slice::IterMut<'a, V>,
287    pos: usize,
288    ids: PhantomData<I>,
289}
290
291impl<'a, I: EntityId, V> Iterator for IterMut<'a, I, V> {
292    type Item = (I, &'a mut V);
293    fn next(&mut self) -> Option<(I, &'a mut V)> {
294        let val = self.vals.next()?;
295        let id = I::from_idx(self.pos);
296        self.pos += 1;
297        Some((id, val))
298    }
299}
300
301impl<'a, I: EntityId, V> DoubleEndedIterator for IterMut<'a, I, V> {
302    fn next_back(&mut self) -> Option<(I, &'a mut V)> {
303        let val = self.vals.next_back()?;
304        Some((I::from_idx(self.pos + self.vals.len()), val))
305    }
306}
307
308impl<'a, I: EntityId, V> ExactSizeIterator for IterMut<'a, I, V> {
309    fn len(&self) -> usize {
310        self.vals.len()
311    }
312}
313
314/// Iterator of `(id, value)` pairs.
315#[derive(Clone, Debug)]
316pub struct IntoIter<I, V> {
317    vals: std::vec::IntoIter<V>,
318    pos: usize,
319    ids: PhantomData<I>,
320}
321
322impl<I: EntityId, V> Iterator for IntoIter<I, V> {
323    type Item = (I, V);
324    fn next(&mut self) -> Option<(I, V)> {
325        let val = self.vals.next()?;
326        let id = I::from_idx(self.pos);
327        self.pos += 1;
328        Some((id, val))
329    }
330}
331
332impl<I: EntityId, V> DoubleEndedIterator for IntoIter<I, V> {
333    fn next_back(&mut self) -> Option<(I, V)> {
334        let val = self.vals.next_back()?;
335        Some((I::from_idx(self.pos + self.vals.len()), val))
336    }
337}
338
339impl<I: EntityId, V> ExactSizeIterator for IntoIter<I, V> {
340    fn len(&self) -> usize {
341        self.vals.len()
342    }
343}
344
345impl<I: EntityId, V> FromIterator<V> for EntityVec<I, V> {
346    fn from_iter<T>(iter: T) -> Self
347    where
348        T: IntoIterator<Item = V>,
349    {
350        Self {
351            vals: Vec::from_iter(iter),
352            ids: PhantomData,
353        }
354    }
355}
356
357impl<I: EntityId, V> Extend<V> for EntityVec<I, V> {
358    fn extend<T: IntoIterator<Item = V>>(&mut self, iter: T) {
359        self.vals.extend(iter);
360    }
361}