1#![allow(clippy::pedantic, clippy::all)]
2
3extern crate alloc;
9
10use alloc::vec::Vec;
11use core::fmt;
12use core::marker::PhantomData;
13use core::ops::{Index, IndexMut};
14use core::slice;
15use alloc::vec;
16use core::iter::Enumerate;
17
18pub trait EntityRef: Copy + Eq {
21 fn new(_: usize) -> Self;
24
25 fn index(self) -> usize;
27}
28
29#[macro_export]
31macro_rules! entity_impl {
32 ($entity:ident) => {
34 impl $crate::EntityRef for $entity {
35 #[inline]
36 fn new(index: usize) -> Self {
37 debug_assert!(index < (u32::MAX as usize));
38 $entity(index as u32)
39 }
40
41 #[inline]
42 fn index(self) -> usize {
43 self.0 as usize
44 }
45 }
46
47 impl $entity {
48 #[allow(dead_code, reason = "macro-generated code")]
50 #[inline]
51 pub fn from_u32(x: u32) -> Self {
52 debug_assert!(x < u32::MAX);
53 $entity(x)
54 }
55
56 #[allow(dead_code, reason = "macro-generated code")]
58 #[inline]
59 pub fn as_u32(self) -> u32 {
60 self.0
61 }
62
63 #[allow(dead_code, reason = "macro-generated code")]
71 #[inline]
72 pub fn as_bits(self) -> u32 {
73 self.0
74 }
75
76 #[allow(dead_code, reason = "macro-generated code")]
84 #[inline]
85 pub fn from_bits(x: u32) -> Self {
86 $entity(x)
87 }
88 }
89 };
90
91 ($entity:ident, $display_prefix:expr) => {
94 $crate::entity_impl!($entity);
95
96 impl core::fmt::Display for $entity {
97 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
98 write!(f, concat!($display_prefix, "{}"), self.0)
99 }
100 }
101
102 impl core::fmt::Debug for $entity {
103 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
104 (self as &dyn core::fmt::Display).fmt(f)
105 }
106 }
107 };
108
109 ($entity:ident, $display_prefix:expr, $arg:ident, $to_expr:expr, $from_expr:expr) => {
112 impl $crate::EntityRef for $entity {
113 #[inline]
114 fn new(index: usize) -> Self {
115 debug_assert!(index < (u32::MAX as usize));
116 let $arg = index as u32;
117 $to_expr
118 }
119
120 #[inline]
121 fn index(self) -> usize {
122 let $arg = self;
123 $from_expr as usize
124 }
125 }
126
127 impl $crate::packed_option::ReservedValue for $entity {
128 #[inline]
129 fn reserved_value() -> $entity {
130 $entity::from_u32(u32::MAX)
131 }
132
133 #[inline]
134 fn is_reserved_value(&self) -> bool {
135 self.as_u32() == u32::MAX
136 }
137 }
138
139 impl $entity {
140 #[allow(dead_code, reason = "macro-generated code")]
142 #[inline]
143 pub fn from_u32(x: u32) -> Self {
144 debug_assert!(x < u32::MAX);
145 let $arg = x;
146 $to_expr
147 }
148
149 #[allow(dead_code, reason = "macro-generated code")]
151 #[inline]
152 pub fn as_u32(self) -> u32 {
153 let $arg = self;
154 $from_expr
155 }
156 }
157
158 impl core::fmt::Display for $entity {
159 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
160 write!(f, concat!($display_prefix, "{}"), self.as_u32())
161 }
162 }
163
164 impl core::fmt::Debug for $entity {
165 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
166 (self as &dyn core::fmt::Display).fmt(f)
167 }
168 }
169 };
170}
171
172#[derive(Clone, Hash, PartialEq, Eq)]
188pub struct PrimaryMap<K, V>
189where
190 K: EntityRef,
191{
192 elems: Vec<V>,
193 unused: PhantomData<K>,
194}
195
196impl<K, V> PrimaryMap<K, V>
197where
198 K: EntityRef,
199{
200 pub fn new() -> Self {
202 Self {
203 elems: Vec::new(),
204 unused: PhantomData,
205 }
206 }
207
208 pub fn with_capacity(capacity: usize) -> Self {
210 Self {
211 elems: Vec::with_capacity(capacity),
212 unused: PhantomData,
213 }
214 }
215
216 pub fn is_valid(&self, k: K) -> bool {
218 k.index() < self.elems.len()
219 }
220
221 pub fn get(&self, k: K) -> Option<&V> {
223 self.elems.get(k.index())
224 }
225
226 pub fn get_range(&self, range: core::ops::Range<K>) -> Option<&[V]> {
228 self.elems.get(range.start.index()..range.end.index())
229 }
230
231 pub fn get_mut(&mut self, k: K) -> Option<&mut V> {
233 self.elems.get_mut(k.index())
234 }
235
236 pub fn is_empty(&self) -> bool {
238 self.elems.is_empty()
239 }
240
241 pub fn len(&self) -> usize {
243 self.elems.len()
244 }
245
246 pub fn keys(&self) -> Keys<K> {
248 Keys::with_len(self.elems.len())
249 }
250
251 pub fn values(&self) -> slice::Iter<'_, V> {
253 self.elems.iter()
254 }
255
256 pub fn values_mut(&mut self) -> slice::IterMut<'_, V> {
258 self.elems.iter_mut()
259 }
260
261 pub fn as_values_slice(&self) -> &[V] {
263 &self.elems
264 }
265
266 pub fn iter(&self) -> Iter<'_, K, V> {
268 Iter::new(self.elems.iter())
269 }
270
271 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
273 IterMut::new(self.elems.iter_mut())
274 }
275
276 pub fn clear(&mut self) {
278 self.elems.clear()
279 }
280
281 pub fn next_key(&self) -> K {
283 K::new(self.elems.len())
284 }
285
286 pub fn push(&mut self, v: V) -> K {
288 let k = self.next_key();
289 self.elems.push(v);
290 k
291 }
292
293 pub fn last(&self) -> Option<(K, &V)> {
295 let len = self.elems.len();
296 let last = self.elems.last()?;
297 Some((K::new(len - 1), last))
298 }
299
300 pub fn last_mut(&mut self) -> Option<(K, &mut V)> {
302 let len = self.elems.len();
303 let last = self.elems.last_mut()?;
304 Some((K::new(len - 1), last))
305 }
306
307 pub fn reserve(&mut self, additional: usize) {
309 self.elems.reserve(additional)
310 }
311
312 pub fn reserve_exact(&mut self, additional: usize) {
314 self.elems.reserve_exact(additional)
315 }
316
317 pub fn shrink_to_fit(&mut self) {
319 self.elems.shrink_to_fit()
320 }
321
322 pub fn get_disjoint_mut<const N: usize>(
327 &mut self,
328 indices: [K; N],
329 ) -> Result<[&mut V; N], slice::GetDisjointMutError> {
330 self.elems.get_disjoint_mut(indices.map(|k| k.index()))
331 }
332
333 pub fn binary_search_values_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<K, K>
345 where
346 F: FnMut(&'a V) -> B,
347 B: Ord,
348 {
349 self.elems
350 .binary_search_by_key(b, f)
351 .map(|i| K::new(i))
352 .map_err(|i| K::new(i))
353 }
354
355 pub fn get_raw_mut(&mut self, k: K) -> Option<*mut V> {
364 if k.index() < self.elems.len() {
365 unsafe { Some(self.elems.as_mut_ptr().add(k.index())) }
369 } else {
370 None
371 }
372 }
373}
374
375impl<K, V> Default for PrimaryMap<K, V>
376where
377 K: EntityRef,
378{
379 fn default() -> PrimaryMap<K, V> {
380 PrimaryMap::new()
381 }
382}
383
384impl<K, V> Index<K> for PrimaryMap<K, V>
387where
388 K: EntityRef,
389{
390 type Output = V;
391
392 fn index(&self, k: K) -> &V {
393 &self.elems[k.index()]
394 }
395}
396
397impl<K, V> IndexMut<K> for PrimaryMap<K, V>
399where
400 K: EntityRef,
401{
402 fn index_mut(&mut self, k: K) -> &mut V {
403 &mut self.elems[k.index()]
404 }
405}
406
407impl<K, V> IntoIterator for PrimaryMap<K, V>
408where
409 K: EntityRef,
410{
411 type Item = (K, V);
412 type IntoIter = IntoIter<K, V>;
413
414 fn into_iter(self) -> Self::IntoIter {
415 IntoIter::new(self.elems.into_iter())
416 }
417}
418
419impl<'a, K, V> IntoIterator for &'a PrimaryMap<K, V>
420where
421 K: EntityRef,
422{
423 type Item = (K, &'a V);
424 type IntoIter = Iter<'a, K, V>;
425
426 fn into_iter(self) -> Self::IntoIter {
427 Iter::new(self.elems.iter())
428 }
429}
430
431impl<'a, K, V> IntoIterator for &'a mut PrimaryMap<K, V>
432where
433 K: EntityRef,
434{
435 type Item = (K, &'a mut V);
436 type IntoIter = IterMut<'a, K, V>;
437
438 fn into_iter(self) -> Self::IntoIter {
439 IterMut::new(self.elems.iter_mut())
440 }
441}
442
443impl<K, V> FromIterator<V> for PrimaryMap<K, V>
444where
445 K: EntityRef,
446{
447 fn from_iter<T>(iter: T) -> Self
448 where
449 T: IntoIterator<Item = V>,
450 {
451 Self {
452 elems: Vec::from_iter(iter),
453 unused: PhantomData,
454 }
455 }
456}
457
458impl<K, V> Extend<V> for PrimaryMap<K, V>
459where
460 K: EntityRef,
461{
462 fn extend<T>(&mut self, iter: T)
463 where
464 T: IntoIterator<Item = V>,
465 {
466 self.elems.extend(iter);
467 }
468}
469
470impl<K, V> From<Vec<V>> for PrimaryMap<K, V>
471where
472 K: EntityRef,
473{
474 fn from(elems: Vec<V>) -> Self {
475 Self {
476 elems,
477 unused: PhantomData,
478 }
479 }
480}
481
482impl<K, V> From<PrimaryMap<K, V>> for Vec<V>
483where
484 K: EntityRef,
485{
486 fn from(map: PrimaryMap<K, V>) -> Self {
487 map.elems
488 }
489}
490
491impl<K: EntityRef + fmt::Debug, V: fmt::Debug> fmt::Debug for PrimaryMap<K, V> {
492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493 let mut struct_ = f.debug_struct("PrimaryMap");
494 for (k, v) in self {
495 struct_.field(&alloc::format!("{k:?}"), v);
496 }
497 struct_.finish()
498 }
499}
500
501pub struct Keys<K: EntityRef> {
507 pos: usize,
508 rev_pos: usize,
509 unused: PhantomData<K>,
510}
511
512impl<K: EntityRef> Keys<K> {
513 pub fn with_len(len: usize) -> Self {
515 Self {
516 pos: 0,
517 rev_pos: len,
518 unused: PhantomData,
519 }
520 }
521}
522
523impl<K: EntityRef> Iterator for Keys<K> {
524 type Item = K;
525
526 fn next(&mut self) -> Option<Self::Item> {
527 if self.pos < self.rev_pos {
528 let k = K::new(self.pos);
529 self.pos += 1;
530 Some(k)
531 } else {
532 None
533 }
534 }
535
536 fn size_hint(&self) -> (usize, Option<usize>) {
537 let size = self.rev_pos - self.pos;
538 (size, Some(size))
539 }
540}
541
542impl<K: EntityRef> DoubleEndedIterator for Keys<K> {
543 fn next_back(&mut self) -> Option<Self::Item> {
544 if self.rev_pos > self.pos {
545 let k = K::new(self.rev_pos - 1);
546 self.rev_pos -= 1;
547 Some(k)
548 } else {
549 None
550 }
551 }
552}
553
554impl<K: EntityRef> ExactSizeIterator for Keys<K> {}
555
556pub struct Iter<'a, K: EntityRef, V>
558where
559 V: 'a,
560{
561 enumerate: Enumerate<slice::Iter<'a, V>>,
562 unused: PhantomData<K>,
563}
564
565impl<'a, K: EntityRef, V> Iter<'a, K, V> {
566 pub fn new(iter: slice::Iter<'a, V>) -> Self {
569 Self {
570 enumerate: iter.enumerate(),
571 unused: PhantomData,
572 }
573 }
574}
575
576impl<'a, K: EntityRef, V> Iterator for Iter<'a, K, V> {
577 type Item = (K, &'a V);
578
579 fn next(&mut self) -> Option<Self::Item> {
580 self.enumerate.next().map(|(i, v)| (K::new(i), v))
581 }
582
583 fn size_hint(&self) -> (usize, Option<usize>) {
584 self.enumerate.size_hint()
585 }
586}
587
588impl<'a, K: EntityRef, V> DoubleEndedIterator for Iter<'a, K, V> {
589 fn next_back(&mut self) -> Option<Self::Item> {
590 self.enumerate.next_back().map(|(i, v)| (K::new(i), v))
591 }
592}
593
594impl<'a, K: EntityRef, V> ExactSizeIterator for Iter<'a, K, V> {}
595
596pub struct IterMut<'a, K: EntityRef, V>
598where
599 V: 'a,
600{
601 enumerate: Enumerate<slice::IterMut<'a, V>>,
602 unused: PhantomData<K>,
603}
604
605impl<'a, K: EntityRef, V> IterMut<'a, K, V> {
606 pub fn new(iter: slice::IterMut<'a, V>) -> Self {
609 Self {
610 enumerate: iter.enumerate(),
611 unused: PhantomData,
612 }
613 }
614}
615
616impl<'a, K: EntityRef, V> Iterator for IterMut<'a, K, V> {
617 type Item = (K, &'a mut V);
618
619 fn next(&mut self) -> Option<Self::Item> {
620 self.enumerate.next().map(|(i, v)| (K::new(i), v))
621 }
622
623 fn size_hint(&self) -> (usize, Option<usize>) {
624 self.enumerate.size_hint()
625 }
626}
627
628impl<'a, K: EntityRef, V> DoubleEndedIterator for IterMut<'a, K, V> {
629 fn next_back(&mut self) -> Option<Self::Item> {
630 self.enumerate.next_back().map(|(i, v)| (K::new(i), v))
631 }
632}
633
634impl<'a, K: EntityRef, V> ExactSizeIterator for IterMut<'a, K, V> {}
635
636pub struct IntoIter<K: EntityRef, V> {
638 enumerate: Enumerate<vec::IntoIter<V>>,
639 unused: PhantomData<K>,
640}
641
642impl<K: EntityRef, V> IntoIter<K, V> {
643 pub fn new(iter: vec::IntoIter<V>) -> Self {
646 Self {
647 enumerate: iter.enumerate(),
648 unused: PhantomData,
649 }
650 }
651}
652
653impl<K: EntityRef, V> Iterator for IntoIter<K, V> {
654 type Item = (K, V);
655
656 fn next(&mut self) -> Option<Self::Item> {
657 self.enumerate.next().map(|(i, v)| (K::new(i), v))
658 }
659
660 fn size_hint(&self) -> (usize, Option<usize>) {
661 self.enumerate.size_hint()
662 }
663}
664
665impl<K: EntityRef, V> DoubleEndedIterator for IntoIter<K, V> {
666 fn next_back(&mut self) -> Option<Self::Item> {
667 self.enumerate.next_back().map(|(i, v)| (K::new(i), v))
668 }
669}
670
671impl<K: EntityRef, V> ExactSizeIterator for IntoIter<K, V> {}