bevy_ecs/entity/
index_map.rs

1//! Contains the [`EntityIndexMap`] type, an [`IndexMap`] pre-configured to use [`EntityHash`] hashing.
2//!
3//! This module is a lightweight wrapper around `indexmap`'s [`IndexMap`] that is more performant for [`Entity`] keys.
4
5use core::{
6    cmp::Ordering,
7    fmt::{self, Debug, Formatter},
8    hash::{BuildHasher, Hash, Hasher},
9    iter::FusedIterator,
10    marker::PhantomData,
11    ops::{
12        Bound, Deref, DerefMut, Index, IndexMut, Range, RangeBounds, RangeFrom, RangeFull,
13        RangeInclusive, RangeTo, RangeToInclusive,
14    },
15    ptr,
16};
17
18#[cfg(feature = "bevy_reflect")]
19use bevy_reflect::Reflect;
20pub use indexmap::map::Entry;
21use indexmap::map::{self, IndexMap, IntoValues, ValuesMut};
22
23use super::{Entity, EntityEquivalent, EntityHash, EntitySetIterator};
24
25use bevy_platform::prelude::Box;
26
27/// A [`IndexMap`] pre-configured to use [`EntityHash`] hashing.
28#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
29#[cfg_attr(feature = "serialize", derive(serde::Deserialize, serde::Serialize))]
30#[derive(Debug, Clone)]
31pub struct EntityIndexMap<V>(pub(crate) IndexMap<Entity, V, EntityHash>);
32
33impl<V> EntityIndexMap<V> {
34    /// Creates an empty `EntityIndexMap`.
35    ///
36    /// Equivalent to [`IndexMap::with_hasher(EntityHash)`].
37    ///
38    /// [`IndexMap::with_hasher(EntityHash)`]: IndexMap::with_hasher
39    pub const fn new() -> Self {
40        Self(IndexMap::with_hasher(EntityHash))
41    }
42
43    /// Creates an empty `EntityIndexMap` with the specified capacity.
44    ///
45    /// Equivalent to [`IndexMap::with_capacity_and_hasher(n, EntityHash)`].
46    ///
47    /// [`IndexMap:with_capacity_and_hasher(n, EntityHash)`]: IndexMap::with_capacity_and_hasher
48    pub fn with_capacity(n: usize) -> Self {
49        Self(IndexMap::with_capacity_and_hasher(n, EntityHash))
50    }
51
52    /// Returns the inner [`IndexMap`].
53    pub fn into_inner(self) -> IndexMap<Entity, V, EntityHash> {
54        self.0
55    }
56
57    /// Returns a slice of all the key-value pairs in the map.
58    ///
59    /// Equivalent to [`IndexMap::as_slice`].
60    pub fn as_slice(&self) -> &Slice<V> {
61        // SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
62        unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
63    }
64
65    /// Returns a mutable slice of all the key-value pairs in the map.
66    ///
67    /// Equivalent to [`IndexMap::as_mut_slice`].
68    pub fn as_mut_slice(&mut self) -> &mut Slice<V> {
69        // SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
70        unsafe { Slice::from_slice_unchecked_mut(self.0.as_mut_slice()) }
71    }
72
73    /// Converts into a boxed slice of all the key-value pairs in the map.
74    ///
75    /// Equivalent to [`IndexMap::into_boxed_slice`].
76    pub fn into_boxed_slice(self) -> Box<Slice<V>> {
77        // SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
78        unsafe { Slice::from_boxed_slice_unchecked(self.0.into_boxed_slice()) }
79    }
80
81    /// Returns a slice of key-value pairs in the given range of indices.
82    ///
83    /// Equivalent to [`IndexMap::get_range`].
84    pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Slice<V>> {
85        self.0.get_range(range).map(|slice|
86            // SAFETY: EntityIndexSetSlice is a transparent wrapper around indexmap::set::Slice.
87            unsafe { Slice::from_slice_unchecked(slice) })
88    }
89
90    /// Returns a mutable slice of key-value pairs in the given range of indices.
91    ///
92    /// Equivalent to [`IndexMap::get_range_mut`].
93    pub fn get_range_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Option<&mut Slice<V>> {
94        self.0.get_range_mut(range).map(|slice|
95            // SAFETY: EntityIndexSetSlice is a transparent wrapper around indexmap::set::Slice.
96            unsafe { Slice::from_slice_unchecked_mut(slice) })
97    }
98
99    /// Return an iterator over the key-value pairs of the map, in their order.
100    ///
101    /// Equivalent to [`IndexMap::iter`].
102    pub fn iter(&self) -> Iter<'_, V> {
103        Iter(self.0.iter(), PhantomData)
104    }
105
106    /// Return a mutable iterator over the key-value pairs of the map, in their order.
107    ///
108    /// Equivalent to [`IndexMap::iter_mut`].
109    pub fn iter_mut(&mut self) -> IterMut<'_, V> {
110        IterMut(self.0.iter_mut(), PhantomData)
111    }
112
113    /// Clears the `IndexMap` in the given index range, returning those
114    /// key-value pairs as a drain iterator.
115    ///
116    /// Equivalent to [`IndexMap::drain`].
117    pub fn drain<R: RangeBounds<usize>>(&mut self, range: R) -> Drain<'_, V> {
118        Drain(self.0.drain(range), PhantomData)
119    }
120
121    /// Return an iterator over the keys of the map, in their order.
122    ///
123    /// Equivalent to [`IndexMap::keys`].
124    pub fn keys(&self) -> Keys<'_, V> {
125        Keys(self.0.keys(), PhantomData)
126    }
127
128    /// Return an owning iterator over the keys of the map, in their order.
129    ///
130    /// Equivalent to [`IndexMap::into_keys`].
131    pub fn into_keys(self) -> IntoKeys<V> {
132        IntoKeys(self.0.into_keys(), PhantomData)
133    }
134}
135
136impl<V> Default for EntityIndexMap<V> {
137    fn default() -> Self {
138        Self(Default::default())
139    }
140}
141
142impl<V> Deref for EntityIndexMap<V> {
143    type Target = IndexMap<Entity, V, EntityHash>;
144
145    fn deref(&self) -> &Self::Target {
146        &self.0
147    }
148}
149
150impl<V> DerefMut for EntityIndexMap<V> {
151    fn deref_mut(&mut self) -> &mut Self::Target {
152        &mut self.0
153    }
154}
155
156impl<'a, V: Copy> Extend<(&'a Entity, &'a V)> for EntityIndexMap<V> {
157    fn extend<T: IntoIterator<Item = (&'a Entity, &'a V)>>(&mut self, iter: T) {
158        self.0.extend(iter);
159    }
160}
161
162impl<V> Extend<(Entity, V)> for EntityIndexMap<V> {
163    fn extend<T: IntoIterator<Item = (Entity, V)>>(&mut self, iter: T) {
164        self.0.extend(iter);
165    }
166}
167
168impl<V, const N: usize> From<[(Entity, V); N]> for EntityIndexMap<V> {
169    fn from(value: [(Entity, V); N]) -> Self {
170        Self(IndexMap::from_iter(value))
171    }
172}
173
174impl<V> FromIterator<(Entity, V)> for EntityIndexMap<V> {
175    fn from_iter<I: IntoIterator<Item = (Entity, V)>>(iterable: I) -> Self {
176        Self(IndexMap::from_iter(iterable))
177    }
178}
179
180impl<V, Q: EntityEquivalent + ?Sized> Index<&Q> for EntityIndexMap<V> {
181    type Output = V;
182    fn index(&self, key: &Q) -> &V {
183        self.0.index(&key.entity())
184    }
185}
186
187impl<V> Index<(Bound<usize>, Bound<usize>)> for EntityIndexMap<V> {
188    type Output = Slice<V>;
189    fn index(&self, key: (Bound<usize>, Bound<usize>)) -> &Self::Output {
190        // SAFETY: The source IndexMap uses EntityHash.
191        unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
192    }
193}
194
195impl<V> Index<Range<usize>> for EntityIndexMap<V> {
196    type Output = Slice<V>;
197    fn index(&self, key: Range<usize>) -> &Self::Output {
198        // SAFETY: The source IndexMap uses EntityHash.
199        unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
200    }
201}
202
203impl<V> Index<RangeFrom<usize>> for EntityIndexMap<V> {
204    type Output = Slice<V>;
205    fn index(&self, key: RangeFrom<usize>) -> &Self::Output {
206        // SAFETY: The source IndexMap uses EntityHash.
207        unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
208    }
209}
210
211impl<V> Index<RangeFull> for EntityIndexMap<V> {
212    type Output = Slice<V>;
213    fn index(&self, key: RangeFull) -> &Self::Output {
214        // SAFETY: The source IndexMap uses EntityHash.
215        unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
216    }
217}
218
219impl<V> Index<RangeInclusive<usize>> for EntityIndexMap<V> {
220    type Output = Slice<V>;
221    fn index(&self, key: RangeInclusive<usize>) -> &Self::Output {
222        // SAFETY: The source IndexMap uses EntityHash.
223        unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
224    }
225}
226
227impl<V> Index<RangeTo<usize>> for EntityIndexMap<V> {
228    type Output = Slice<V>;
229    fn index(&self, key: RangeTo<usize>) -> &Self::Output {
230        // SAFETY: The source IndexMap uses EntityHash.
231        unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
232    }
233}
234
235impl<V> Index<RangeToInclusive<usize>> for EntityIndexMap<V> {
236    type Output = Slice<V>;
237    fn index(&self, key: RangeToInclusive<usize>) -> &Self::Output {
238        // SAFETY: The source IndexMap uses EntityHash.
239        unsafe { Slice::from_slice_unchecked(self.0.index(key)) }
240    }
241}
242
243impl<V> Index<usize> for EntityIndexMap<V> {
244    type Output = V;
245    fn index(&self, key: usize) -> &V {
246        self.0.index(key)
247    }
248}
249
250impl<V, Q: EntityEquivalent + ?Sized> IndexMut<&Q> for EntityIndexMap<V> {
251    fn index_mut(&mut self, key: &Q) -> &mut V {
252        self.0.index_mut(&key.entity())
253    }
254}
255
256impl<V> IndexMut<(Bound<usize>, Bound<usize>)> for EntityIndexMap<V> {
257    fn index_mut(&mut self, key: (Bound<usize>, Bound<usize>)) -> &mut Self::Output {
258        // SAFETY: The source IndexMap uses EntityHash.
259        unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
260    }
261}
262
263impl<V> IndexMut<Range<usize>> for EntityIndexMap<V> {
264    fn index_mut(&mut self, key: Range<usize>) -> &mut Self::Output {
265        // SAFETY: The source IndexMap uses EntityHash.
266        unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
267    }
268}
269
270impl<V> IndexMut<RangeFrom<usize>> for EntityIndexMap<V> {
271    fn index_mut(&mut self, key: RangeFrom<usize>) -> &mut Self::Output {
272        // SAFETY: The source IndexMap uses EntityHash.
273        unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
274    }
275}
276
277impl<V> IndexMut<RangeFull> for EntityIndexMap<V> {
278    fn index_mut(&mut self, key: RangeFull) -> &mut Self::Output {
279        // SAFETY: The source IndexMap uses EntityHash.
280        unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
281    }
282}
283
284impl<V> IndexMut<RangeInclusive<usize>> for EntityIndexMap<V> {
285    fn index_mut(&mut self, key: RangeInclusive<usize>) -> &mut Self::Output {
286        // SAFETY: The source IndexMap uses EntityHash.
287        unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
288    }
289}
290
291impl<V> IndexMut<RangeTo<usize>> for EntityIndexMap<V> {
292    fn index_mut(&mut self, key: RangeTo<usize>) -> &mut Self::Output {
293        // SAFETY: The source IndexMap uses EntityHash.
294        unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
295    }
296}
297
298impl<V> IndexMut<RangeToInclusive<usize>> for EntityIndexMap<V> {
299    fn index_mut(&mut self, key: RangeToInclusive<usize>) -> &mut Self::Output {
300        // SAFETY: The source IndexMap uses EntityHash.
301        unsafe { Slice::from_slice_unchecked_mut(self.0.index_mut(key)) }
302    }
303}
304
305impl<V> IndexMut<usize> for EntityIndexMap<V> {
306    fn index_mut(&mut self, key: usize) -> &mut V {
307        self.0.index_mut(key)
308    }
309}
310
311impl<'a, V> IntoIterator for &'a EntityIndexMap<V> {
312    type Item = (&'a Entity, &'a V);
313    type IntoIter = Iter<'a, V>;
314
315    fn into_iter(self) -> Self::IntoIter {
316        Iter(self.0.iter(), PhantomData)
317    }
318}
319
320impl<'a, V> IntoIterator for &'a mut EntityIndexMap<V> {
321    type Item = (&'a Entity, &'a mut V);
322    type IntoIter = IterMut<'a, V>;
323
324    fn into_iter(self) -> Self::IntoIter {
325        IterMut(self.0.iter_mut(), PhantomData)
326    }
327}
328
329impl<V> IntoIterator for EntityIndexMap<V> {
330    type Item = (Entity, V);
331    type IntoIter = IntoIter<V>;
332
333    fn into_iter(self) -> Self::IntoIter {
334        IntoIter(self.0.into_iter(), PhantomData)
335    }
336}
337
338impl<V1, V2, S2> PartialEq<IndexMap<Entity, V2, S2>> for EntityIndexMap<V1>
339where
340    V1: PartialEq<V2>,
341    S2: BuildHasher,
342{
343    fn eq(&self, other: &IndexMap<Entity, V2, S2>) -> bool {
344        self.0.eq(other)
345    }
346}
347
348impl<V1, V2> PartialEq<EntityIndexMap<V2>> for EntityIndexMap<V1>
349where
350    V1: PartialEq<V2>,
351{
352    fn eq(&self, other: &EntityIndexMap<V2>) -> bool {
353        self.0.eq(other)
354    }
355}
356
357impl<V: Eq> Eq for EntityIndexMap<V> {}
358
359/// A dynamically-sized slice of key-value pairs in an [`EntityIndexMap`].
360///
361/// Equivalent to an [`indexmap::map::Slice<V>`] whose source [`IndexMap`]
362/// uses [`EntityHash`].
363#[repr(transparent)]
364pub struct Slice<V, S = EntityHash>(PhantomData<S>, map::Slice<Entity, V>);
365
366impl<V> Slice<V> {
367    /// Returns an empty slice.    
368    ///
369    /// Equivalent to [`map::Slice::new`].
370    pub const fn new<'a>() -> &'a Self {
371        // SAFETY: The source slice is empty.
372        unsafe { Self::from_slice_unchecked(map::Slice::new()) }
373    }
374
375    /// Returns an empty mutable slice.
376    ///
377    /// Equivalent to [`map::Slice::new_mut`].
378    pub fn new_mut<'a>() -> &'a mut Self {
379        // SAFETY: The source slice is empty.
380        unsafe { Self::from_slice_unchecked_mut(map::Slice::new_mut()) }
381    }
382
383    /// Constructs a [`entity::index_map::Slice`] from a [`indexmap::map::Slice`] unsafely.
384    ///
385    /// # Safety
386    ///
387    /// `slice` must stem from an [`IndexMap`] using [`EntityHash`].
388    ///
389    /// [`entity::index_map::Slice`]: `crate::entity::index_map::Slice`
390    pub const unsafe fn from_slice_unchecked(slice: &map::Slice<Entity, V>) -> &Self {
391        // SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
392        unsafe { &*(ptr::from_ref(slice) as *const Self) }
393    }
394
395    /// Constructs a [`entity::index_map::Slice`] from a [`indexmap::map::Slice`] unsafely.
396    ///
397    /// # Safety
398    ///
399    /// `slice` must stem from an [`IndexMap`] using [`EntityHash`].
400    ///
401    /// [`entity::index_map::Slice`]: `crate::entity::index_map::Slice`
402    pub const unsafe fn from_slice_unchecked_mut(slice: &mut map::Slice<Entity, V>) -> &mut Self {
403        // SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
404        unsafe { &mut *(ptr::from_mut(slice) as *mut Self) }
405    }
406
407    /// Casts `self` to the inner slice.
408    pub const fn as_inner(&self) -> &map::Slice<Entity, V> {
409        &self.1
410    }
411
412    /// Constructs a boxed [`entity::index_map::Slice`] from a boxed [`indexmap::map::Slice`] unsafely.
413    ///
414    /// # Safety
415    ///
416    /// `slice` must stem from an [`IndexMap`] using [`EntityHash`].
417    ///
418    /// [`entity::index_map::Slice`]: `crate::entity::index_map::Slice`
419    pub unsafe fn from_boxed_slice_unchecked(slice: Box<map::Slice<Entity, V>>) -> Box<Self> {
420        // SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
421        unsafe { Box::from_raw(Box::into_raw(slice) as *mut Self) }
422    }
423
424    /// Casts a reference to `self` to the inner slice.
425    #[expect(
426        clippy::borrowed_box,
427        reason = "We wish to access the Box API of the inner type, without consuming it."
428    )]
429    pub fn as_boxed_inner(self: &Box<Self>) -> &Box<map::Slice<Entity, V>> {
430        // SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
431        unsafe { &*(ptr::from_ref(self).cast::<Box<map::Slice<Entity, V>>>()) }
432    }
433
434    /// Casts `self` to the inner slice.
435    pub fn into_boxed_inner(self: Box<Self>) -> Box<map::Slice<Entity, V>> {
436        // SAFETY: Slice is a transparent wrapper around indexmap::map::Slice.
437        unsafe { Box::from_raw(Box::into_raw(self) as *mut map::Slice<Entity, V>) }
438    }
439
440    /// Get a key-value pair by index, with mutable access to the value.
441    ///
442    /// Equivalent to [`map::Slice::get_index_mut`].
443    pub fn get_index_mut(&mut self, index: usize) -> Option<(&Entity, &mut V)> {
444        self.1.get_index_mut(index)
445    }
446
447    /// Returns a slice of key-value pairs in the given range of indices.
448    ///
449    /// Equivalent to [`map::Slice::get_range`].
450    pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Self> {
451        self.1.get_range(range).map(|slice|
452            // SAFETY: This a subslice of a valid slice.
453            unsafe { Self::from_slice_unchecked(slice) })
454    }
455
456    /// Returns a mutable slice of key-value pairs in the given range of indices.
457    ///
458    /// Equivalent to [`map::Slice::get_range_mut`].
459    pub fn get_range_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Option<&mut Self> {
460        self.1.get_range_mut(range).map(|slice|
461            // SAFETY: This a subslice of a valid slice.
462            unsafe { Self::from_slice_unchecked_mut(slice) })
463    }
464
465    /// Get the first key-value pair, with mutable access to the value.
466    ///
467    /// Equivalent to [`map::Slice::first_mut`].
468    pub fn first_mut(&mut self) -> Option<(&Entity, &mut V)> {
469        self.1.first_mut()
470    }
471
472    /// Get the last key-value pair, with mutable access to the value.
473    ///
474    /// Equivalent to [`map::Slice::last_mut`].
475    pub fn last_mut(&mut self) -> Option<(&Entity, &mut V)> {
476        self.1.last_mut()
477    }
478
479    /// Divides one slice into two at an index.
480    ///
481    /// Equivalent to [`map::Slice::split_at`].
482    pub fn split_at(&self, index: usize) -> (&Self, &Self) {
483        let (slice_1, slice_2) = self.1.split_at(index);
484        // SAFETY: These are subslices of a valid slice.
485        unsafe {
486            (
487                Self::from_slice_unchecked(slice_1),
488                Self::from_slice_unchecked(slice_2),
489            )
490        }
491    }
492
493    /// Divides one mutable slice into two at an index.
494    ///
495    /// Equivalent to [`map::Slice::split_at_mut`].
496    pub fn split_at_mut(&mut self, index: usize) -> (&mut Self, &mut Self) {
497        let (slice_1, slice_2) = self.1.split_at_mut(index);
498        // SAFETY: These are subslices of a valid slice.
499        unsafe {
500            (
501                Self::from_slice_unchecked_mut(slice_1),
502                Self::from_slice_unchecked_mut(slice_2),
503            )
504        }
505    }
506
507    /// Returns the first key-value pair and the rest of the slice,
508    /// or `None` if it is empty.
509    ///
510    /// Equivalent to [`map::Slice::split_first`].
511    pub fn split_first(&self) -> Option<((&Entity, &V), &Self)> {
512        self.1.split_first().map(|(first, rest)| {
513            (
514                first,
515                // SAFETY: This a subslice of a valid slice.
516                unsafe { Self::from_slice_unchecked(rest) },
517            )
518        })
519    }
520
521    /// Returns the first key-value pair and the rest of the slice,
522    /// with mutable access to the value, or `None` if it is empty.
523    ///
524    /// Equivalent to [`map::Slice::split_first_mut`].
525    pub fn split_first_mut(&mut self) -> Option<((&Entity, &mut V), &mut Self)> {
526        self.1.split_first_mut().map(|(first, rest)| {
527            (
528                first,
529                // SAFETY: This a subslice of a valid slice.
530                unsafe { Self::from_slice_unchecked_mut(rest) },
531            )
532        })
533    }
534
535    /// Returns the last key-value pair and the rest of the slice,
536    /// or `None` if it is empty.
537    ///
538    /// Equivalent to [`map::Slice::split_last`].
539    pub fn split_last(&self) -> Option<((&Entity, &V), &Self)> {
540        self.1.split_last().map(|(last, rest)| {
541            (
542                last,
543                // SAFETY: This a subslice of a valid slice.
544                unsafe { Self::from_slice_unchecked(rest) },
545            )
546        })
547    }
548
549    /// Returns the last key-value pair and the rest of the slice,
550    /// with mutable access to the value, or `None` if it is empty.
551    ///
552    /// Equivalent to [`map::Slice::split_last_mut`].
553    pub fn split_last_mut(&mut self) -> Option<((&Entity, &mut V), &mut Self)> {
554        self.1.split_last_mut().map(|(last, rest)| {
555            (
556                last,
557                // SAFETY: This a subslice of a valid slice.
558                unsafe { Self::from_slice_unchecked_mut(rest) },
559            )
560        })
561    }
562
563    /// Return an iterator over the key-value pairs of the map slice.
564    ///
565    /// Equivalent to [`map::Slice::iter`].
566    pub fn iter(&self) -> Iter<'_, V> {
567        Iter(self.1.iter(), PhantomData)
568    }
569
570    /// Return an iterator over the key-value pairs of the map slice.
571    ///
572    /// Equivalent to [`map::Slice::iter_mut`].
573    pub fn iter_mut(&mut self) -> IterMut<'_, V> {
574        IterMut(self.1.iter_mut(), PhantomData)
575    }
576
577    /// Return an iterator over the keys of the map slice.
578    ///
579    /// Equivalent to [`map::Slice::keys`].
580    pub fn keys(&self) -> Keys<'_, V> {
581        Keys(self.1.keys(), PhantomData)
582    }
583
584    /// Return an owning iterator over the keys of the map slice.
585    ///
586    /// Equivalent to [`map::Slice::into_keys`].
587    pub fn into_keys(self: Box<Self>) -> IntoKeys<V> {
588        IntoKeys(self.into_boxed_inner().into_keys(), PhantomData)
589    }
590
591    /// Return an iterator over mutable references to the values of the map slice.
592    ///
593    /// Equivalent to [`map::Slice::values_mut`].
594    pub fn values_mut(&mut self) -> ValuesMut<'_, Entity, V> {
595        self.1.values_mut()
596    }
597
598    /// Return an owning iterator over the values of the map slice.
599    ///
600    /// Equivalent to [`map::Slice::into_values`].
601    pub fn into_values(self: Box<Self>) -> IntoValues<Entity, V> {
602        self.into_boxed_inner().into_values()
603    }
604}
605
606impl<V> Deref for Slice<V> {
607    type Target = map::Slice<Entity, V>;
608
609    fn deref(&self) -> &Self::Target {
610        &self.1
611    }
612}
613
614impl<V: Debug> Debug for Slice<V> {
615    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
616        f.debug_tuple("Slice")
617            .field(&self.0)
618            .field(&&self.1)
619            .finish()
620    }
621}
622
623impl<V: Clone> Clone for Box<Slice<V>> {
624    fn clone(&self) -> Self {
625        // SAFETY: This a clone of a valid slice.
626        unsafe { Slice::from_boxed_slice_unchecked(self.as_boxed_inner().clone()) }
627    }
628}
629
630impl<V> Default for &Slice<V> {
631    fn default() -> Self {
632        // SAFETY: The source slice is empty.
633        unsafe { Slice::from_slice_unchecked(<&map::Slice<Entity, V>>::default()) }
634    }
635}
636
637impl<V> Default for &mut Slice<V> {
638    fn default() -> Self {
639        // SAFETY: The source slice is empty.
640        unsafe { Slice::from_slice_unchecked_mut(<&mut map::Slice<Entity, V>>::default()) }
641    }
642}
643
644impl<V> Default for Box<Slice<V>> {
645    fn default() -> Self {
646        // SAFETY: The source slice is empty.
647        unsafe { Slice::from_boxed_slice_unchecked(<Box<map::Slice<Entity, V>>>::default()) }
648    }
649}
650
651impl<V: Copy> From<&Slice<V>> for Box<Slice<V>> {
652    fn from(value: &Slice<V>) -> Self {
653        // SAFETY: This slice is a copy of a valid slice.
654        unsafe { Slice::from_boxed_slice_unchecked(value.1.into()) }
655    }
656}
657
658impl<V: Hash> Hash for Slice<V> {
659    fn hash<H: Hasher>(&self, state: &mut H) {
660        self.1.hash(state);
661    }
662}
663
664impl<'a, V> IntoIterator for &'a Slice<V> {
665    type Item = (&'a Entity, &'a V);
666    type IntoIter = Iter<'a, V>;
667
668    fn into_iter(self) -> Self::IntoIter {
669        Iter(self.1.iter(), PhantomData)
670    }
671}
672
673impl<'a, V> IntoIterator for &'a mut Slice<V> {
674    type Item = (&'a Entity, &'a mut V);
675    type IntoIter = IterMut<'a, V>;
676
677    fn into_iter(self) -> Self::IntoIter {
678        IterMut(self.1.iter_mut(), PhantomData)
679    }
680}
681
682impl<V> IntoIterator for Box<Slice<V>> {
683    type Item = (Entity, V);
684    type IntoIter = IntoIter<V>;
685
686    fn into_iter(self) -> Self::IntoIter {
687        IntoIter(self.into_boxed_inner().into_iter(), PhantomData)
688    }
689}
690
691impl<V: PartialOrd> PartialOrd for Slice<V> {
692    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
693        self.1.partial_cmp(&other.1)
694    }
695}
696
697impl<V: Ord> Ord for Slice<V> {
698    fn cmp(&self, other: &Self) -> Ordering {
699        self.1.cmp(other)
700    }
701}
702
703impl<V: PartialEq> PartialEq for Slice<V> {
704    fn eq(&self, other: &Self) -> bool {
705        self.1 == other.1
706    }
707}
708
709impl<V: Eq> Eq for Slice<V> {}
710
711impl<V> Index<(Bound<usize>, Bound<usize>)> for Slice<V> {
712    type Output = Self;
713    fn index(&self, key: (Bound<usize>, Bound<usize>)) -> &Self {
714        // SAFETY: This a subslice of a valid slice.
715        unsafe { Self::from_slice_unchecked(self.1.index(key)) }
716    }
717}
718
719impl<V> Index<Range<usize>> for Slice<V> {
720    type Output = Self;
721    fn index(&self, key: Range<usize>) -> &Self {
722        // SAFETY: This a subslice of a valid slice.
723        unsafe { Self::from_slice_unchecked(self.1.index(key)) }
724    }
725}
726
727impl<V> Index<RangeFrom<usize>> for Slice<V> {
728    type Output = Self;
729    fn index(&self, key: RangeFrom<usize>) -> &Self {
730        // SAFETY: This a subslice of a valid slice.
731        unsafe { Self::from_slice_unchecked(self.1.index(key)) }
732    }
733}
734
735impl<V> Index<RangeFull> for Slice<V> {
736    type Output = Self;
737    fn index(&self, key: RangeFull) -> &Self {
738        // SAFETY: This a subslice of a valid slice.
739        unsafe { Self::from_slice_unchecked(self.1.index(key)) }
740    }
741}
742
743impl<V> Index<RangeInclusive<usize>> for Slice<V> {
744    type Output = Self;
745    fn index(&self, key: RangeInclusive<usize>) -> &Self {
746        // SAFETY: This a subslice of a valid slice.
747        unsafe { Self::from_slice_unchecked(self.1.index(key)) }
748    }
749}
750
751impl<V> Index<RangeTo<usize>> for Slice<V> {
752    type Output = Self;
753    fn index(&self, key: RangeTo<usize>) -> &Self {
754        // SAFETY: This a subslice of a valid slice.
755        unsafe { Self::from_slice_unchecked(self.1.index(key)) }
756    }
757}
758
759impl<V> Index<RangeToInclusive<usize>> for Slice<V> {
760    type Output = Self;
761    fn index(&self, key: RangeToInclusive<usize>) -> &Self {
762        // SAFETY: This a subslice of a valid slice.
763        unsafe { Self::from_slice_unchecked(self.1.index(key)) }
764    }
765}
766
767impl<V> Index<usize> for Slice<V> {
768    type Output = V;
769    fn index(&self, key: usize) -> &V {
770        self.1.index(key)
771    }
772}
773
774impl<V> IndexMut<(Bound<usize>, Bound<usize>)> for Slice<V> {
775    fn index_mut(&mut self, key: (Bound<usize>, Bound<usize>)) -> &mut Self {
776        // SAFETY: This a subslice of a valid slice.
777        unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
778    }
779}
780
781impl<V> IndexMut<Range<usize>> for Slice<V> {
782    fn index_mut(&mut self, key: Range<usize>) -> &mut Self {
783        // SAFETY: This a subslice of a valid slice.
784        unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
785    }
786}
787
788impl<V> IndexMut<RangeFrom<usize>> for Slice<V> {
789    fn index_mut(&mut self, key: RangeFrom<usize>) -> &mut Self {
790        // SAFETY: This a subslice of a valid slice.
791        unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
792    }
793}
794
795impl<V> IndexMut<RangeFull> for Slice<V> {
796    fn index_mut(&mut self, key: RangeFull) -> &mut Self {
797        // SAFETY: This a subslice of a valid slice.
798        unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
799    }
800}
801
802impl<V> IndexMut<RangeInclusive<usize>> for Slice<V> {
803    fn index_mut(&mut self, key: RangeInclusive<usize>) -> &mut Self {
804        // SAFETY: This a subslice of a valid slice.
805        unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
806    }
807}
808
809impl<V> IndexMut<RangeTo<usize>> for Slice<V> {
810    fn index_mut(&mut self, key: RangeTo<usize>) -> &mut Self {
811        // SAFETY: This a subslice of a valid slice.
812        unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
813    }
814}
815
816impl<V> IndexMut<RangeToInclusive<usize>> for Slice<V> {
817    fn index_mut(&mut self, key: RangeToInclusive<usize>) -> &mut Self {
818        // SAFETY: This a subslice of a valid slice.
819        unsafe { Self::from_slice_unchecked_mut(self.1.index_mut(key)) }
820    }
821}
822
823impl<V> IndexMut<usize> for Slice<V> {
824    fn index_mut(&mut self, key: usize) -> &mut V {
825        self.1.index_mut(key)
826    }
827}
828
829/// An iterator over the entries of an [`EntityIndexMap`].
830///
831/// This `struct` is created by the [`EntityIndexMap::iter`] method.
832/// See its documentation for more.
833pub struct Iter<'a, V, S = EntityHash>(map::Iter<'a, Entity, V>, PhantomData<S>);
834
835impl<'a, V> Iter<'a, V> {
836    /// Returns the inner [`Iter`](map::Iter).
837    pub fn into_inner(self) -> map::Iter<'a, Entity, V> {
838        self.0
839    }
840
841    /// Returns a slice of the remaining entries in the iterator.
842    ///
843    /// Equivalent to [`map::Iter::as_slice`].
844    pub fn as_slice(&self) -> &Slice<V> {
845        // SAFETY: The source IndexMap uses EntityHash.
846        unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
847    }
848}
849
850impl<'a, V> Deref for Iter<'a, V> {
851    type Target = map::Iter<'a, Entity, V>;
852
853    fn deref(&self) -> &Self::Target {
854        &self.0
855    }
856}
857
858impl<'a, V> Iterator for Iter<'a, V> {
859    type Item = (&'a Entity, &'a V);
860
861    fn next(&mut self) -> Option<Self::Item> {
862        self.0.next()
863    }
864
865    fn size_hint(&self) -> (usize, Option<usize>) {
866        self.0.size_hint()
867    }
868}
869
870impl<V> DoubleEndedIterator for Iter<'_, V> {
871    fn next_back(&mut self) -> Option<Self::Item> {
872        self.0.next_back()
873    }
874}
875
876impl<V> ExactSizeIterator for Iter<'_, V> {}
877
878impl<V> FusedIterator for Iter<'_, V> {}
879
880impl<V> Clone for Iter<'_, V> {
881    fn clone(&self) -> Self {
882        Self(self.0.clone(), PhantomData)
883    }
884}
885
886impl<V: Debug> Debug for Iter<'_, V> {
887    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
888        f.debug_tuple("Iter").field(&self.0).field(&self.1).finish()
889    }
890}
891
892impl<V> Default for Iter<'_, V> {
893    fn default() -> Self {
894        Self(Default::default(), PhantomData)
895    }
896}
897
898/// A mutable iterator over the entries of an [`EntityIndexMap`].
899///
900/// This `struct` is created by the [`EntityIndexMap::iter_mut`] method.
901/// See its documentation for more.
902pub struct IterMut<'a, V, S = EntityHash>(map::IterMut<'a, Entity, V>, PhantomData<S>);
903
904impl<'a, V> IterMut<'a, V> {
905    /// Returns the inner [`IterMut`](map::IterMut).
906    pub fn into_inner(self) -> map::IterMut<'a, Entity, V> {
907        self.0
908    }
909
910    /// Returns a slice of the remaining entries in the iterator.
911    ///
912    /// Equivalent to [`map::IterMut::as_slice`].
913    pub fn as_slice(&self) -> &Slice<V> {
914        // SAFETY: The source IndexMap uses EntityHash.
915        unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
916    }
917
918    /// Returns a mutable slice of the remaining entries in the iterator.
919    ///
920    /// Equivalent to [`map::IterMut::into_slice`].
921    pub fn into_slice(self) -> &'a mut Slice<V> {
922        // SAFETY: The source IndexMap uses EntityHash.
923        unsafe { Slice::from_slice_unchecked_mut(self.0.into_slice()) }
924    }
925}
926
927impl<'a, V> Deref for IterMut<'a, V> {
928    type Target = map::IterMut<'a, Entity, V>;
929
930    fn deref(&self) -> &Self::Target {
931        &self.0
932    }
933}
934
935impl<'a, V> Iterator for IterMut<'a, V> {
936    type Item = (&'a Entity, &'a mut V);
937
938    fn next(&mut self) -> Option<Self::Item> {
939        self.0.next()
940    }
941
942    fn size_hint(&self) -> (usize, Option<usize>) {
943        self.0.size_hint()
944    }
945}
946
947impl<V> DoubleEndedIterator for IterMut<'_, V> {
948    fn next_back(&mut self) -> Option<Self::Item> {
949        self.0.next_back()
950    }
951}
952
953impl<V> ExactSizeIterator for IterMut<'_, V> {}
954
955impl<V> FusedIterator for IterMut<'_, V> {}
956
957impl<V: Debug> Debug for IterMut<'_, V> {
958    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
959        f.debug_tuple("IterMut")
960            .field(&self.0)
961            .field(&self.1)
962            .finish()
963    }
964}
965
966impl<V> Default for IterMut<'_, V> {
967    fn default() -> Self {
968        Self(Default::default(), PhantomData)
969    }
970}
971
972/// An owning iterator over the entries of an [`IndexMap`].
973///
974/// This `struct` is created by the [`IndexMap::into_iter`] method
975/// (provided by the [`IntoIterator`] trait). See its documentation for more.
976pub struct IntoIter<V, S = EntityHash>(map::IntoIter<Entity, V>, PhantomData<S>);
977
978impl<V> IntoIter<V> {
979    /// Returns the inner [`IntoIter`](map::IntoIter).
980    pub fn into_inner(self) -> map::IntoIter<Entity, V> {
981        self.0
982    }
983
984    /// Returns a slice of the remaining entries in the iterator.
985    ///
986    /// Equivalent to [`map::IntoIter::as_slice`].
987    pub fn as_slice(&self) -> &Slice<V> {
988        // SAFETY: The source IndexMap uses EntityHash.
989        unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
990    }
991
992    /// Returns a mutable slice of the remaining entries in the iterator.
993    ///
994    /// Equivalent to [`map::IntoIter::as_mut_slice`].
995    pub fn as_mut_slice(&mut self) -> &mut Slice<V> {
996        // SAFETY: The source IndexMap uses EntityHash.
997        unsafe { Slice::from_slice_unchecked_mut(self.0.as_mut_slice()) }
998    }
999}
1000
1001impl<V> Deref for IntoIter<V> {
1002    type Target = map::IntoIter<Entity, V>;
1003
1004    fn deref(&self) -> &Self::Target {
1005        &self.0
1006    }
1007}
1008
1009impl<V> Iterator for IntoIter<V> {
1010    type Item = (Entity, V);
1011
1012    fn next(&mut self) -> Option<Self::Item> {
1013        self.0.next()
1014    }
1015
1016    fn size_hint(&self) -> (usize, Option<usize>) {
1017        self.0.size_hint()
1018    }
1019}
1020
1021impl<V> DoubleEndedIterator for IntoIter<V> {
1022    fn next_back(&mut self) -> Option<Self::Item> {
1023        self.0.next_back()
1024    }
1025}
1026
1027impl<V> ExactSizeIterator for IntoIter<V> {}
1028
1029impl<V> FusedIterator for IntoIter<V> {}
1030
1031impl<V: Clone> Clone for IntoIter<V> {
1032    fn clone(&self) -> Self {
1033        Self(self.0.clone(), PhantomData)
1034    }
1035}
1036
1037impl<V: Debug> Debug for IntoIter<V> {
1038    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1039        f.debug_tuple("IntoIter")
1040            .field(&self.0)
1041            .field(&self.1)
1042            .finish()
1043    }
1044}
1045
1046impl<V> Default for IntoIter<V> {
1047    fn default() -> Self {
1048        Self(Default::default(), PhantomData)
1049    }
1050}
1051
1052/// A draining iterator over the entries of an [`EntityIndexMap`].
1053///
1054/// This `struct` is created by the [`EntityIndexMap::drain`] method.
1055/// See its documentation for more.
1056pub struct Drain<'a, V, S = EntityHash>(map::Drain<'a, Entity, V>, PhantomData<S>);
1057
1058impl<'a, V> Drain<'a, V> {
1059    /// Returns the inner [`Drain`](map::Drain).
1060    pub fn into_inner(self) -> map::Drain<'a, Entity, V> {
1061        self.0
1062    }
1063
1064    /// Returns a slice of the remaining entries in the iterator.
1065    ///
1066    /// Equivalent to [`map::Drain::as_slice`].
1067    pub fn as_slice(&self) -> &Slice<V> {
1068        // SAFETY: The source IndexMap uses EntityHash.
1069        unsafe { Slice::from_slice_unchecked(self.0.as_slice()) }
1070    }
1071}
1072
1073impl<'a, V> Deref for Drain<'a, V> {
1074    type Target = map::Drain<'a, Entity, V>;
1075
1076    fn deref(&self) -> &Self::Target {
1077        &self.0
1078    }
1079}
1080
1081impl<V> Iterator for Drain<'_, V> {
1082    type Item = (Entity, V);
1083
1084    fn next(&mut self) -> Option<Self::Item> {
1085        self.0.next()
1086    }
1087
1088    fn size_hint(&self) -> (usize, Option<usize>) {
1089        self.0.size_hint()
1090    }
1091}
1092
1093impl<V> DoubleEndedIterator for Drain<'_, V> {
1094    fn next_back(&mut self) -> Option<Self::Item> {
1095        self.0.next_back()
1096    }
1097}
1098
1099impl<V> ExactSizeIterator for Drain<'_, V> {}
1100
1101impl<V> FusedIterator for Drain<'_, V> {}
1102
1103impl<V: Debug> Debug for Drain<'_, V> {
1104    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1105        f.debug_tuple("Drain")
1106            .field(&self.0)
1107            .field(&self.1)
1108            .finish()
1109    }
1110}
1111
1112/// An iterator over the keys of an [`EntityIndexMap`].
1113///
1114/// This `struct` is created by the [`EntityIndexMap::keys`] method.
1115/// See its documentation for more.
1116pub struct Keys<'a, V, S = EntityHash>(map::Keys<'a, Entity, V>, PhantomData<S>);
1117
1118impl<'a, V> Keys<'a, V> {
1119    /// Returns the inner [`Keys`](map::Keys).
1120    pub fn into_inner(self) -> map::Keys<'a, Entity, V> {
1121        self.0
1122    }
1123}
1124
1125impl<'a, V, S> Deref for Keys<'a, V, S> {
1126    type Target = map::Keys<'a, Entity, V>;
1127
1128    fn deref(&self) -> &Self::Target {
1129        &self.0
1130    }
1131}
1132
1133impl<'a, V> Iterator for Keys<'a, V> {
1134    type Item = &'a Entity;
1135
1136    fn next(&mut self) -> Option<Self::Item> {
1137        self.0.next()
1138    }
1139
1140    fn size_hint(&self) -> (usize, Option<usize>) {
1141        self.0.size_hint()
1142    }
1143}
1144
1145impl<V> DoubleEndedIterator for Keys<'_, V> {
1146    fn next_back(&mut self) -> Option<Self::Item> {
1147        self.0.next_back()
1148    }
1149}
1150
1151impl<V> ExactSizeIterator for Keys<'_, V> {}
1152
1153impl<V> FusedIterator for Keys<'_, V> {}
1154
1155impl<V> Index<usize> for Keys<'_, V> {
1156    type Output = Entity;
1157
1158    fn index(&self, index: usize) -> &Entity {
1159        self.0.index(index)
1160    }
1161}
1162
1163impl<V> Clone for Keys<'_, V> {
1164    fn clone(&self) -> Self {
1165        Self(self.0.clone(), PhantomData)
1166    }
1167}
1168
1169impl<V: Debug> Debug for Keys<'_, V> {
1170    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1171        f.debug_tuple("Keys").field(&self.0).field(&self.1).finish()
1172    }
1173}
1174
1175impl<V> Default for Keys<'_, V> {
1176    fn default() -> Self {
1177        Self(Default::default(), PhantomData)
1178    }
1179}
1180
1181// SAFETY: Keys stems from a correctly behaving `IndexMap<Entity, V, EntityHash>`.
1182unsafe impl<V> EntitySetIterator for Keys<'_, V> {}
1183
1184/// An owning iterator over the keys of an [`EntityIndexMap`].
1185///
1186/// This `struct` is created by the [`EntityIndexMap::into_keys`] method.
1187/// See its documentation for more.
1188pub struct IntoKeys<V, S = EntityHash>(map::IntoKeys<Entity, V>, PhantomData<S>);
1189
1190impl<V> IntoKeys<V> {
1191    /// Returns the inner [`IntoKeys`](map::IntoKeys).
1192    pub fn into_inner(self) -> map::IntoKeys<Entity, V> {
1193        self.0
1194    }
1195}
1196
1197impl<V> Deref for IntoKeys<V> {
1198    type Target = map::IntoKeys<Entity, V>;
1199
1200    fn deref(&self) -> &Self::Target {
1201        &self.0
1202    }
1203}
1204
1205impl<V> Iterator for IntoKeys<V> {
1206    type Item = Entity;
1207
1208    fn next(&mut self) -> Option<Self::Item> {
1209        self.0.next()
1210    }
1211
1212    fn size_hint(&self) -> (usize, Option<usize>) {
1213        self.0.size_hint()
1214    }
1215}
1216
1217impl<V> DoubleEndedIterator for IntoKeys<V> {
1218    fn next_back(&mut self) -> Option<Self::Item> {
1219        self.0.next_back()
1220    }
1221}
1222
1223impl<V> ExactSizeIterator for IntoKeys<V> {}
1224
1225impl<V> FusedIterator for IntoKeys<V> {}
1226
1227impl<V: Debug> Debug for IntoKeys<V> {
1228    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1229        f.debug_tuple("IntoKeys")
1230            .field(&self.0)
1231            .field(&self.1)
1232            .finish()
1233    }
1234}
1235
1236impl<V> Default for IntoKeys<V> {
1237    fn default() -> Self {
1238        Self(Default::default(), PhantomData)
1239    }
1240}
1241
1242// SAFETY: IntoKeys stems from a correctly behaving `IndexMap<Entity, V, EntityHash>`.
1243unsafe impl<V> EntitySetIterator for IntoKeys<V> {}