1 //! Densely numbered entity references as mapping keys.
2 use crate::EntityRef;
3 use crate::boxed_slice::BoxedSlice;
4 use crate::iter::{IntoIter, Iter, IterMut};
5 use crate::keys::Keys;
6 use alloc::boxed::Box;
7 use alloc::vec::Vec;
8 use core::fmt;
9 use core::marker::PhantomData;
10 use core::ops::{Index, IndexMut};
11 use core::slice;
12 #[cfg(feature = "enable-serde")]
13 use serde_derive::{Deserialize, Serialize};
14 
15 /// A primary mapping `K -> V` allocating dense entity references.
16 ///
17 /// The `PrimaryMap` data structure uses the dense index space to implement a map with a vector.
18 ///
19 /// A primary map contains the main definition of an entity, and it can be used to allocate new
20 /// entity references with the `push` method.
21 ///
22 /// There should only be a single `PrimaryMap` instance for a given `EntityRef` type, otherwise
23 /// conflicting references will be created. Using unknown keys for indexing will cause a panic.
24 ///
25 /// Note that `PrimaryMap` doesn't implement `Deref` or `DerefMut`, which would allow
26 /// `&PrimaryMap<K, V>` to convert to `&[V]`. One of the main advantages of `PrimaryMap` is
27 /// that it only allows indexing with the distinct `EntityRef` key type, so converting to a
28 /// plain slice would make it easier to use incorrectly. To make a slice of a `PrimaryMap`, use
29 /// `into_boxed_slice`.
30 #[derive(Clone, Hash, PartialEq, Eq)]
31 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
32 pub struct PrimaryMap<K, V>
33 where
34     K: EntityRef,
35 {
36     elems: Vec<V>,
37     unused: PhantomData<K>,
38 }
39 
40 impl<K, V> PrimaryMap<K, V>
41 where
42     K: EntityRef,
43 {
44     /// Create a new empty map.
45     pub fn new() -> Self {
46         Self {
47             elems: Vec::new(),
48             unused: PhantomData,
49         }
50     }
51 
52     /// Create a new empty map with the given capacity.
53     pub fn with_capacity(capacity: usize) -> Self {
54         Self {
55             elems: Vec::with_capacity(capacity),
56             unused: PhantomData,
57         }
58     }
59 
60     /// Check if `k` is a valid key in the map.
61     pub fn is_valid(&self, k: K) -> bool {
62         k.index() < self.elems.len()
63     }
64 
65     /// Get the element at `k` if it exists.
66     pub fn get(&self, k: K) -> Option<&V> {
67         self.elems.get(k.index())
68     }
69 
70     /// Get the slice of values associated with the given range of keys, if any.
71     pub fn get_range(&self, range: core::ops::Range<K>) -> Option<&[V]> {
72         self.elems.get(range.start.index()..range.end.index())
73     }
74 
75     /// Get the element at `k` if it exists, mutable version.
76     pub fn get_mut(&mut self, k: K) -> Option<&mut V> {
77         self.elems.get_mut(k.index())
78     }
79 
80     /// Is this map completely empty?
81     pub fn is_empty(&self) -> bool {
82         self.elems.is_empty()
83     }
84 
85     /// Get the total number of entity references created.
86     pub fn len(&self) -> usize {
87         self.elems.len()
88     }
89 
90     /// Iterate over all the keys in this map.
91     pub fn keys(&self) -> Keys<K> {
92         Keys::with_len(self.elems.len())
93     }
94 
95     /// Iterate over all the values in this map.
96     pub fn values(&self) -> slice::Iter<'_, V> {
97         self.elems.iter()
98     }
99 
100     /// Iterate over all the values in this map, mutable edition.
101     pub fn values_mut(&mut self) -> slice::IterMut<'_, V> {
102         self.elems.iter_mut()
103     }
104 
105     /// Get this map's underlying values as a slice.
106     pub fn as_values_slice(&self) -> &[V] {
107         &self.elems
108     }
109 
110     /// Iterate over all the keys and values in this map.
111     pub fn iter(&self) -> Iter<'_, K, V> {
112         Iter::new(self.elems.iter())
113     }
114 
115     /// Iterate over all the keys and values in this map, mutable edition.
116     pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
117         IterMut::new(self.elems.iter_mut())
118     }
119 
120     /// Remove all entries from this map.
121     pub fn clear(&mut self) {
122         self.elems.clear()
123     }
124 
125     /// Get the key that will be assigned to the next pushed value.
126     pub fn next_key(&self) -> K {
127         K::new(self.elems.len())
128     }
129 
130     /// Append `v` to the mapping, assigning a new key which is returned.
131     pub fn push(&mut self, v: V) -> K {
132         let k = self.next_key();
133         self.elems.push(v);
134         k
135     }
136 
137     /// Returns the last element that was inserted in the map.
138     pub fn last(&self) -> Option<(K, &V)> {
139         let len = self.elems.len();
140         let last = self.elems.last()?;
141         Some((K::new(len - 1), last))
142     }
143 
144     /// Returns the last element that was inserted in the map.
145     pub fn last_mut(&mut self) -> Option<(K, &mut V)> {
146         let len = self.elems.len();
147         let last = self.elems.last_mut()?;
148         Some((K::new(len - 1), last))
149     }
150 
151     /// Reserves capacity for at least `additional` more elements to be inserted.
152     pub fn reserve(&mut self, additional: usize) {
153         self.elems.reserve(additional)
154     }
155 
156     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted.
157     pub fn reserve_exact(&mut self, additional: usize) {
158         self.elems.reserve_exact(additional)
159     }
160 
161     /// Shrinks the capacity of the `PrimaryMap` as much as possible.
162     pub fn shrink_to_fit(&mut self) {
163         self.elems.shrink_to_fit()
164     }
165 
166     /// Consumes this `PrimaryMap` and produces a `BoxedSlice`.
167     pub fn into_boxed_slice(self) -> BoxedSlice<K, V> {
168         unsafe { BoxedSlice::<K, V>::from_raw(Box::<[V]>::into_raw(self.elems.into_boxed_slice())) }
169     }
170 
171     /// Returns mutable references to many elements at once.
172     ///
173     /// Returns an error if an element does not exist, or if the same key was passed more than
174     /// once.
175     pub fn get_disjoint_mut<const N: usize>(
176         &mut self,
177         indices: [K; N],
178     ) -> Result<[&mut V; N], slice::GetDisjointMutError> {
179         self.elems.get_disjoint_mut(indices.map(|k| k.index()))
180     }
181 
182     /// Performs a binary search on the values with a key extraction function.
183     ///
184     /// Assumes that the values are sorted by the key extracted by the function.
185     ///
186     /// If the value is found then `Ok(K)` is returned, containing the entity key
187     /// of the matching value.
188     ///
189     /// If there are multiple matches, then any one of the matches could be returned.
190     ///
191     /// If the value is not found then Err(K) is returned, containing the entity key
192     /// where a matching element could be inserted while maintaining sorted order.
193     pub fn binary_search_values_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<K, K>
194     where
195         F: FnMut(&'a V) -> B,
196         B: Ord,
197     {
198         self.elems
199             .binary_search_by_key(b, f)
200             .map(|i| K::new(i))
201             .map_err(|i| K::new(i))
202     }
203 
204     /// Analog of `get_raw` except that a raw pointer is returned rather than a
205     /// mutable reference.
206     ///
207     /// The default accessors of items in [`PrimaryMap`] will invalidate all
208     /// previous borrows obtained from the map according to miri. This function
209     /// can be used to acquire a pointer and then subsequently acquire a second
210     /// pointer later on without invalidating the first one. In other words
211     /// this is only here to help borrow two elements simultaneously with miri.
212     pub fn get_raw_mut(&mut self, k: K) -> Option<*mut V> {
213         if k.index() < self.elems.len() {
214             // SAFETY: the `add` function requires that the index is in-bounds
215             // with respect to the allocation which is satisfied here due to
216             // the bounds-check above.
217             unsafe { Some(self.elems.as_mut_ptr().add(k.index())) }
218         } else {
219             None
220         }
221     }
222 }
223 
224 impl<K, V> Default for PrimaryMap<K, V>
225 where
226     K: EntityRef,
227 {
228     fn default() -> PrimaryMap<K, V> {
229         PrimaryMap::new()
230     }
231 }
232 
233 /// Immutable indexing into an `PrimaryMap`.
234 /// The indexed value must be in the map.
235 impl<K, V> Index<K> for PrimaryMap<K, V>
236 where
237     K: EntityRef,
238 {
239     type Output = V;
240 
241     fn index(&self, k: K) -> &V {
242         &self.elems[k.index()]
243     }
244 }
245 
246 /// Mutable indexing into an `PrimaryMap`.
247 impl<K, V> IndexMut<K> for PrimaryMap<K, V>
248 where
249     K: EntityRef,
250 {
251     fn index_mut(&mut self, k: K) -> &mut V {
252         &mut self.elems[k.index()]
253     }
254 }
255 
256 impl<K, V> IntoIterator for PrimaryMap<K, V>
257 where
258     K: EntityRef,
259 {
260     type Item = (K, V);
261     type IntoIter = IntoIter<K, V>;
262 
263     fn into_iter(self) -> Self::IntoIter {
264         IntoIter::new(self.elems.into_iter())
265     }
266 }
267 
268 impl<'a, K, V> IntoIterator for &'a PrimaryMap<K, V>
269 where
270     K: EntityRef,
271 {
272     type Item = (K, &'a V);
273     type IntoIter = Iter<'a, K, V>;
274 
275     fn into_iter(self) -> Self::IntoIter {
276         Iter::new(self.elems.iter())
277     }
278 }
279 
280 impl<'a, K, V> IntoIterator for &'a mut PrimaryMap<K, V>
281 where
282     K: EntityRef,
283 {
284     type Item = (K, &'a mut V);
285     type IntoIter = IterMut<'a, K, V>;
286 
287     fn into_iter(self) -> Self::IntoIter {
288         IterMut::new(self.elems.iter_mut())
289     }
290 }
291 
292 impl<K, V> FromIterator<V> for PrimaryMap<K, V>
293 where
294     K: EntityRef,
295 {
296     fn from_iter<T>(iter: T) -> Self
297     where
298         T: IntoIterator<Item = V>,
299     {
300         Self {
301             elems: Vec::from_iter(iter),
302             unused: PhantomData,
303         }
304     }
305 }
306 
307 impl<K, V> Extend<V> for PrimaryMap<K, V>
308 where
309     K: EntityRef,
310 {
311     fn extend<T>(&mut self, iter: T)
312     where
313         T: IntoIterator<Item = V>,
314     {
315         self.elems.extend(iter);
316     }
317 }
318 
319 impl<K, V> From<Vec<V>> for PrimaryMap<K, V>
320 where
321     K: EntityRef,
322 {
323     fn from(elems: Vec<V>) -> Self {
324         Self {
325             elems,
326             unused: PhantomData,
327         }
328     }
329 }
330 
331 impl<K, V> From<PrimaryMap<K, V>> for Vec<V>
332 where
333     K: EntityRef,
334 {
335     fn from(map: PrimaryMap<K, V>) -> Self {
336         map.elems
337     }
338 }
339 
340 impl<K: EntityRef + fmt::Debug, V: fmt::Debug> fmt::Debug for PrimaryMap<K, V> {
341     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342         let mut struct_ = f.debug_struct("PrimaryMap");
343         for (k, v) in self {
344             struct_.field(&alloc::format!("{k:?}"), v);
345         }
346         struct_.finish()
347     }
348 }
349 
350 #[cfg(test)]
351 mod tests {
352     use super::*;
353 
354     // `EntityRef` impl for testing.
355     #[derive(Clone, Copy, Debug, PartialEq, Eq)]
356     struct E(u32);
357 
358     impl EntityRef for E {
359         fn new(i: usize) -> Self {
360             E(i as u32)
361         }
362         fn index(self) -> usize {
363             self.0 as usize
364         }
365     }
366 
367     #[test]
368     fn basic() {
369         let r0 = E(0);
370         let r1 = E(1);
371         let m = PrimaryMap::<E, isize>::new();
372 
373         let v: Vec<E> = m.keys().collect();
374         assert_eq!(v, []);
375 
376         assert!(!m.is_valid(r0));
377         assert!(!m.is_valid(r1));
378     }
379 
380     #[test]
381     fn push() {
382         let mut m = PrimaryMap::new();
383         let k0: E = m.push(12);
384         let k1 = m.push(33);
385 
386         assert_eq!(m[k0], 12);
387         assert_eq!(m[k1], 33);
388 
389         let v: Vec<E> = m.keys().collect();
390         assert_eq!(v, [k0, k1]);
391     }
392 
393     #[test]
394     fn iter() {
395         let mut m: PrimaryMap<E, usize> = PrimaryMap::new();
396         m.push(12);
397         m.push(33);
398 
399         let mut i = 0;
400         for (key, value) in &m {
401             assert_eq!(key.index(), i);
402             match i {
403                 0 => assert_eq!(*value, 12),
404                 1 => assert_eq!(*value, 33),
405                 _ => panic!(),
406             }
407             i += 1;
408         }
409         i = 0;
410         for (key_mut, value_mut) in m.iter_mut() {
411             assert_eq!(key_mut.index(), i);
412             match i {
413                 0 => assert_eq!(*value_mut, 12),
414                 1 => assert_eq!(*value_mut, 33),
415                 _ => panic!(),
416             }
417             i += 1;
418         }
419     }
420 
421     #[test]
422     fn iter_rev() {
423         let mut m: PrimaryMap<E, usize> = PrimaryMap::new();
424         m.push(12);
425         m.push(33);
426 
427         let mut i = 2;
428         for (key, value) in m.iter().rev() {
429             i -= 1;
430             assert_eq!(key.index(), i);
431             match i {
432                 0 => assert_eq!(*value, 12),
433                 1 => assert_eq!(*value, 33),
434                 _ => panic!(),
435             }
436         }
437 
438         i = 2;
439         for (key, value) in m.iter_mut().rev() {
440             i -= 1;
441             assert_eq!(key.index(), i);
442             match i {
443                 0 => assert_eq!(*value, 12),
444                 1 => assert_eq!(*value, 33),
445                 _ => panic!(),
446             }
447         }
448     }
449     #[test]
450     fn keys() {
451         let mut m: PrimaryMap<E, usize> = PrimaryMap::new();
452         m.push(12);
453         m.push(33);
454 
455         let mut i = 0;
456         for key in m.keys() {
457             assert_eq!(key.index(), i);
458             i += 1;
459         }
460     }
461 
462     #[test]
463     fn keys_rev() {
464         let mut m: PrimaryMap<E, usize> = PrimaryMap::new();
465         m.push(12);
466         m.push(33);
467 
468         let mut i = 2;
469         for key in m.keys().rev() {
470             i -= 1;
471             assert_eq!(key.index(), i);
472         }
473     }
474 
475     #[test]
476     fn values() {
477         let mut m: PrimaryMap<E, usize> = PrimaryMap::new();
478         m.push(12);
479         m.push(33);
480 
481         let mut i = 0;
482         for value in m.values() {
483             match i {
484                 0 => assert_eq!(*value, 12),
485                 1 => assert_eq!(*value, 33),
486                 _ => panic!(),
487             }
488             i += 1;
489         }
490         i = 0;
491         for value_mut in m.values_mut() {
492             match i {
493                 0 => assert_eq!(*value_mut, 12),
494                 1 => assert_eq!(*value_mut, 33),
495                 _ => panic!(),
496             }
497             i += 1;
498         }
499     }
500 
501     #[test]
502     fn values_rev() {
503         let mut m: PrimaryMap<E, usize> = PrimaryMap::new();
504         m.push(12);
505         m.push(33);
506 
507         let mut i = 2;
508         for value in m.values().rev() {
509             i -= 1;
510             match i {
511                 0 => assert_eq!(*value, 12),
512                 1 => assert_eq!(*value, 33),
513                 _ => panic!(),
514             }
515         }
516         i = 2;
517         for value_mut in m.values_mut().rev() {
518             i -= 1;
519             match i {
520                 0 => assert_eq!(*value_mut, 12),
521                 1 => assert_eq!(*value_mut, 33),
522                 _ => panic!(),
523             }
524         }
525     }
526 
527     #[test]
528     fn from_iter() {
529         let mut m: PrimaryMap<E, usize> = PrimaryMap::new();
530         m.push(12);
531         m.push(33);
532 
533         let n = m.values().collect::<PrimaryMap<E, _>>();
534         assert!(m.len() == n.len());
535         for (me, ne) in m.values().zip(n.values()) {
536             assert!(*me == **ne);
537         }
538     }
539 
540     #[test]
541     fn from_vec() {
542         let mut m: PrimaryMap<E, usize> = PrimaryMap::new();
543         m.push(12);
544         m.push(33);
545 
546         let n = PrimaryMap::<E, &usize>::from(m.values().collect::<Vec<_>>());
547         assert!(m.len() == n.len());
548         for (me, ne) in m.values().zip(n.values()) {
549             assert!(*me == **ne);
550         }
551     }
552 
553     #[test]
554     fn get_many_mut() {
555         let mut m: PrimaryMap<E, usize> = PrimaryMap::new();
556         let _0 = m.push(0);
557         let _1 = m.push(1);
558         let _2 = m.push(2);
559 
560         assert_eq!([&mut 0, &mut 2], m.get_disjoint_mut([_0, _2]).unwrap());
561         assert_eq!(
562             m.get_disjoint_mut([_0, _0]),
563             Err(slice::GetDisjointMutError::OverlappingIndices)
564         );
565         assert_eq!(
566             m.get_disjoint_mut([E(4)]),
567             Err(slice::GetDisjointMutError::IndexOutOfBounds)
568         );
569     }
570 }
571