Skip to main content

bevy_ecs/entity/
index_map.rs

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