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::mem;
11 use core::ops::{Index, IndexMut};
12 use core::slice;
13 #[cfg(feature = "enable-serde")]
14 use serde_derive::{Deserialize, Serialize};
15 
16 /// A primary mapping `K -> V` allocating dense entity references.
17 ///
18 /// The `PrimaryMap` data structure uses the dense index space to implement a map with a vector.
19 ///
20 /// A primary map contains the main definition of an entity, and it can be used to allocate new
21 /// entity references with the `push` method.
22 ///
23 /// There should only be a single `PrimaryMap` instance for a given `EntityRef` type, otherwise
24 /// conflicting references will be created. Using unknown keys for indexing will cause a panic.
25 ///
26 /// Note that `PrimaryMap` doesn't implement `Deref` or `DerefMut`, which would allow
27 /// `&PrimaryMap<K, V>` to convert to `&[V]`. One of the main advantages of `PrimaryMap` is
28 /// that it only allows indexing with the distinct `EntityRef` key type, so converting to a
29 /// plain slice would make it easier to use incorrectly. To make a slice of a `PrimaryMap`, use
30 /// `into_boxed_slice`.
31 #[derive(Clone, Hash, PartialEq, Eq)]
32 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
33 pub struct PrimaryMap<K, V>
34 where
35     K: EntityRef,
36 {
37     elems: Vec<V>,
38     unused: PhantomData<K>,
39 }
40 
41 impl<K, V> PrimaryMap<K, V>
42 where
43     K: EntityRef,
44 {
45     /// Create a new empty map.
46     pub fn new() -> Self {
47         Self {
48             elems: Vec::new(),
49             unused: PhantomData,
50         }
51     }
52 
53     /// Create a new empty map with the given capacity.
54     pub fn with_capacity(capacity: usize) -> Self {
55         Self {
56             elems: Vec::with_capacity(capacity),
57             unused: PhantomData,
58         }
59     }
60 
61     /// Check if `k` is a valid key in the map.
62     pub fn is_valid(&self, k: K) -> bool {
63         k.index() < self.elems.len()
64     }
65 
66     /// Get the element at `k` if it exists.
67     pub fn get(&self, k: K) -> Option<&V> {
68         self.elems.get(k.index())
69     }
70 
71     /// Get the element at `k` if it exists, mutable version.
72     pub fn get_mut(&mut self, k: K) -> Option<&mut V> {
73         self.elems.get_mut(k.index())
74     }
75 
76     /// Is this map completely empty?
77     pub fn is_empty(&self) -> bool {
78         self.elems.is_empty()
79     }
80 
81     /// Get the total number of entity references created.
82     pub fn len(&self) -> usize {
83         self.elems.len()
84     }
85 
86     /// Iterate over all the keys in this map.
87     pub fn keys(&self) -> Keys<K> {
88         Keys::with_len(self.elems.len())
89     }
90 
91     /// Iterate over all the values in this map.
92     pub fn values(&self) -> slice::Iter<'_, V> {
93         self.elems.iter()
94     }
95 
96     /// Iterate over all the values in this map, mutable edition.
97     pub fn values_mut(&mut self) -> slice::IterMut<'_, V> {
98         self.elems.iter_mut()
99     }
100 
101     /// Iterate over all the keys and values in this map.
102     pub fn iter(&self) -> Iter<'_, K, V> {
103         Iter::new(self.elems.iter())
104     }
105 
106     /// Iterate over all the keys and values in this map, mutable edition.
107     pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
108         IterMut::new(self.elems.iter_mut())
109     }
110 
111     /// Remove all entries from this map.
112     pub fn clear(&mut self) {
113         self.elems.clear()
114     }
115 
116     /// Get the key that will be assigned to the next pushed value.
117     pub fn next_key(&self) -> K {
118         K::new(self.elems.len())
119     }
120 
121     /// Append `v` to the mapping, assigning a new key which is returned.
122     pub fn push(&mut self, v: V) -> K {
123         let k = self.next_key();
124         self.elems.push(v);
125         k
126     }
127 
128     /// Returns the last element that was inserted in the map.
129     pub fn last(&self) -> Option<(K, &V)> {
130         let len = self.elems.len();
131         let last = self.elems.last()?;
132         Some((K::new(len - 1), last))
133     }
134 
135     /// Returns the last element that was inserted in the map.
136     pub fn last_mut(&mut self) -> Option<(K, &mut V)> {
137         let len = self.elems.len();
138         let last = self.elems.last_mut()?;
139         Some((K::new(len - 1), last))
140     }
141 
142     /// Reserves capacity for at least `additional` more elements to be inserted.
143     pub fn reserve(&mut self, additional: usize) {
144         self.elems.reserve(additional)
145     }
146 
147     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted.
148     pub fn reserve_exact(&mut self, additional: usize) {
149         self.elems.reserve_exact(additional)
150     }
151 
152     /// Shrinks the capacity of the `PrimaryMap` as much as possible.
153     pub fn shrink_to_fit(&mut self) {
154         self.elems.shrink_to_fit()
155     }
156 
157     /// Consumes this `PrimaryMap` and produces a `BoxedSlice`.
158     pub fn into_boxed_slice(self) -> BoxedSlice<K, V> {
159         unsafe { BoxedSlice::<K, V>::from_raw(Box::<[V]>::into_raw(self.elems.into_boxed_slice())) }
160     }
161 
162     /// Returns mutable references to many elements at once.
163     ///
164     /// Returns an error if an element does not exist, or if the same key was passed more than
165     /// once.
166     // This implementation is taken from the unstable `get_many_mut`.
167     //
168     // Once it has been stabilised we can call that method directly.
169     pub fn get_many_mut<const N: usize>(
170         &mut self,
171         indices: [K; N],
172     ) -> Result<[&mut V; N], GetManyMutError<K>> {
173         for (i, &idx) in indices.iter().enumerate() {
174             if idx.index() >= self.len() {
175                 return Err(GetManyMutError::DoesNotExist(idx));
176             }
177             for &idx2 in &indices[..i] {
178                 if idx == idx2 {
179                     return Err(GetManyMutError::MultipleOf(idx));
180                 }
181             }
182         }
183 
184         let slice: *mut V = self.elems.as_mut_ptr();
185         let mut arr: mem::MaybeUninit<[&mut V; N]> = mem::MaybeUninit::uninit();
186         let arr_ptr = arr.as_mut_ptr();
187 
188         unsafe {
189             for i in 0..N {
190                 let idx = *indices.get_unchecked(i);
191                 *(*arr_ptr).get_unchecked_mut(i) = &mut *slice.add(idx.index());
192             }
193             Ok(arr.assume_init())
194         }
195     }
196 
197     /// Performs a binary search on the values with a key extraction function.
198     ///
199     /// Assumes that the values are sorted by the key extracted by the function.
200     ///
201     /// If the value is found then `Ok(K)` is returned, containing the entity key
202     /// of the matching value.
203     ///
204     /// If there are multiple matches, then any one of the matches could be returned.
205     ///
206     /// If the value is not found then Err(K) is returned, containing the entity key
207     /// where a matching element could be inserted while maintaining sorted order.
208     pub fn binary_search_values_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<K, K>
209     where
210         F: FnMut(&'a V) -> B,
211         B: Ord,
212     {
213         self.elems
214             .binary_search_by_key(b, f)
215             .map(|i| K::new(i))
216             .map_err(|i| K::new(i))
217     }
218 
219     /// Analog of `get_raw` except that a raw pointer is returned rather than a
220     /// mutable reference.
221     ///
222     /// The default accessors of items in [`PrimaryMap`] will invalidate all
223     /// previous borrows obtained from the map according to miri. This function
224     /// can be used to acquire a pointer and then subsequently acquire a second
225     /// pointer later on without invalidating the first one. In other words
226     /// this is only here to help borrow two elements simultaneously with miri.
227     pub fn get_raw_mut(&mut self, k: K) -> Option<*mut V> {
228         if k.index() < self.elems.len() {
229             // SAFETY: the `add` function requires that the index is in-bounds
230             // with respect to the allocation which is satisfied here due to
231             // the bounds-check above.
232             unsafe { Some(self.elems.as_mut_ptr().add(k.index())) }
233         } else {
234             None
235         }
236     }
237 }
238 
239 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
240 pub enum GetManyMutError<K> {
241     DoesNotExist(K),
242     MultipleOf(K),
243 }
244 
245 impl<K, V> Default for PrimaryMap<K, V>
246 where
247     K: EntityRef,
248 {
249     fn default() -> PrimaryMap<K, V> {
250         PrimaryMap::new()
251     }
252 }
253 
254 /// Immutable indexing into an `PrimaryMap`.
255 /// The indexed value must be in the map.
256 impl<K, V> Index<K> for PrimaryMap<K, V>
257 where
258     K: EntityRef,
259 {
260     type Output = V;
261 
262     fn index(&self, k: K) -> &V {
263         &self.elems[k.index()]
264     }
265 }
266 
267 /// Mutable indexing into an `PrimaryMap`.
268 impl<K, V> IndexMut<K> for PrimaryMap<K, V>
269 where
270     K: EntityRef,
271 {
272     fn index_mut(&mut self, k: K) -> &mut V {
273         &mut self.elems[k.index()]
274     }
275 }
276 
277 impl<K, V> IntoIterator for PrimaryMap<K, V>
278 where
279     K: EntityRef,
280 {
281     type Item = (K, V);
282     type IntoIter = IntoIter<K, V>;
283 
284     fn into_iter(self) -> Self::IntoIter {
285         IntoIter::new(self.elems.into_iter())
286     }
287 }
288 
289 impl<'a, K, V> IntoIterator for &'a PrimaryMap<K, V>
290 where
291     K: EntityRef,
292 {
293     type Item = (K, &'a V);
294     type IntoIter = Iter<'a, K, V>;
295 
296     fn into_iter(self) -> Self::IntoIter {
297         Iter::new(self.elems.iter())
298     }
299 }
300 
301 impl<'a, K, V> IntoIterator for &'a mut PrimaryMap<K, V>
302 where
303     K: EntityRef,
304 {
305     type Item = (K, &'a mut V);
306     type IntoIter = IterMut<'a, K, V>;
307 
308     fn into_iter(self) -> Self::IntoIter {
309         IterMut::new(self.elems.iter_mut())
310     }
311 }
312 
313 impl<K, V> FromIterator<V> for PrimaryMap<K, V>
314 where
315     K: EntityRef,
316 {
317     fn from_iter<T>(iter: T) -> Self
318     where
319         T: IntoIterator<Item = V>,
320     {
321         Self {
322             elems: Vec::from_iter(iter),
323             unused: PhantomData,
324         }
325     }
326 }
327 
328 impl<K, V> From<Vec<V>> for PrimaryMap<K, V>
329 where
330     K: EntityRef,
331 {
332     fn from(elems: Vec<V>) -> Self {
333         Self {
334             elems,
335             unused: PhantomData,
336         }
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_many_mut([_0, _2]).unwrap());
561         assert_eq!(
562             m.get_many_mut([_0, _0]),
563             Err(GetManyMutError::MultipleOf(_0))
564         );
565         assert_eq!(
566             m.get_many_mut([E(4)]),
567             Err(GetManyMutError::DoesNotExist(E(4)))
568         );
569     }
570 }
571