Skip to main content

bevy_ecs/entity/
unique_slice.rs

1//! A wrapper around entity slices with a uniqueness invariant.
2
3use core::{
4    array::TryFromSliceError,
5    borrow::Borrow,
6    cmp::Ordering,
7    fmt::Debug,
8    iter::FusedIterator,
9    ops::{
10        Bound, Deref, Index, IndexMut, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo,
11        RangeToInclusive,
12    },
13    ptr,
14    slice::{self, SliceIndex},
15};
16
17use alloc::{
18    borrow::{Cow, ToOwned},
19    boxed::Box,
20    collections::VecDeque,
21    rc::Rc,
22    vec::Vec,
23};
24
25use bevy_platform::sync::Arc;
26
27use super::{
28    unique_vec::{self, UniqueEntityEquivalentVec},
29    Entity, EntityEquivalent, EntitySet, EntitySetIterator, FromEntitySetIterator,
30    UniqueEntityEquivalentArray, UniqueEntityIter,
31};
32
33/// A slice that contains only unique entities.
34///
35/// This can be obtained by slicing [`UniqueEntityEquivalentVec`].
36///
37/// When `T` is [`Entity`], use [`UniqueEntitySlice`].
38#[repr(transparent)]
39#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
40pub struct UniqueEntityEquivalentSlice<T: EntityEquivalent>([T]);
41
42/// A slice that contains only unique [`Entity`].
43///
44/// This is the default case of a [`UniqueEntityEquivalentSlice`].
45pub type UniqueEntitySlice = UniqueEntityEquivalentSlice<Entity>;
46
47impl<T: EntityEquivalent> UniqueEntityEquivalentSlice<T> {
48    /// Constructs a `UniqueEntityEquivalentSlice` from a [`&[T]`] unsafely.
49    ///
50    /// # Safety
51    ///
52    /// `slice` must contain only unique elements.
53    pub const unsafe fn from_slice_unchecked(slice: &[T]) -> &Self {
54        // SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
55        unsafe { &*(ptr::from_ref(slice) as *const Self) }
56    }
57
58    /// Constructs a `UniqueEntityEquivalentSlice` from a [`&mut [T]`] unsafely.
59    ///
60    /// # Safety
61    ///
62    /// `slice` must contain only unique elements.
63    pub const unsafe fn from_slice_unchecked_mut(slice: &mut [T]) -> &mut Self {
64        // SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
65        unsafe { &mut *(ptr::from_mut(slice) as *mut Self) }
66    }
67
68    /// Casts to `self` to a standard slice.
69    pub const fn as_inner(&self) -> &[T] {
70        &self.0
71    }
72
73    /// Constructs a `UniqueEntityEquivalentSlice` from a [`Box<[T]>`] unsafely.
74    ///
75    /// # Safety
76    ///
77    /// `slice` must contain only unique elements.
78    pub unsafe fn from_boxed_slice_unchecked(slice: Box<[T]>) -> Box<Self> {
79        // SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
80        unsafe { Box::from_raw(Box::into_raw(slice) as *mut Self) }
81    }
82
83    /// Casts `self` to the inner slice.
84    pub fn into_boxed_inner(self: Box<Self>) -> Box<[T]> {
85        // SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
86        unsafe { Box::from_raw(Box::into_raw(self) as *mut [T]) }
87    }
88
89    /// Constructs a `UniqueEntityEquivalentSlice` from a [`Arc<[T]>`] unsafely.
90    ///
91    /// # Safety
92    ///
93    /// `slice` must contain only unique elements.
94    pub unsafe fn from_arc_slice_unchecked(slice: Arc<[T]>) -> Arc<Self> {
95        // SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
96        unsafe { Arc::from_raw(Arc::into_raw(slice) as *mut Self) }
97    }
98
99    /// Casts `self` to the inner slice.
100    pub fn into_arc_inner(this: Arc<Self>) -> Arc<[T]> {
101        // SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
102        unsafe { Arc::from_raw(Arc::into_raw(this) as *mut [T]) }
103    }
104
105    // Constructs a `UniqueEntityEquivalentSlice` from a [`Rc<[T]>`] unsafely.
106    ///
107    /// # Safety
108    ///
109    /// `slice` must contain only unique elements.
110    pub unsafe fn from_rc_slice_unchecked(slice: Rc<[T]>) -> Rc<Self> {
111        // SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
112        unsafe { Rc::from_raw(Rc::into_raw(slice) as *mut Self) }
113    }
114
115    /// Casts `self` to the inner slice.
116    pub fn into_rc_inner(self: Rc<Self>) -> Rc<[T]> {
117        // SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
118        unsafe { Rc::from_raw(Rc::into_raw(self) as *mut [T]) }
119    }
120
121    /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
122    ///
123    /// Equivalent to [`[T]::split_first`](slice::split_first).
124    pub const fn split_first(&self) -> Option<(&T, &Self)> {
125        let Some((first, rest)) = self.0.split_first() else {
126            return None;
127        };
128        // SAFETY: All elements in the original slice are unique.
129        Some((first, unsafe { Self::from_slice_unchecked(rest) }))
130    }
131
132    /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
133    ///
134    /// Equivalent to [`[T]::split_last`](slice::split_last).
135    pub const fn split_last(&self) -> Option<(&T, &Self)> {
136        let Some((last, rest)) = self.0.split_last() else {
137            return None;
138        };
139        // SAFETY: All elements in the original slice are unique.
140        Some((last, unsafe { Self::from_slice_unchecked(rest) }))
141    }
142
143    /// Returns an array reference to the first `N` items in the slice.
144    ///
145    /// Equivalent to [`[T]::first_chunk`](slice::first_chunk).
146    pub const fn first_chunk<const N: usize>(&self) -> Option<&UniqueEntityEquivalentArray<T, N>> {
147        let Some(chunk) = self.0.first_chunk() else {
148            return None;
149        };
150        // SAFETY: All elements in the original slice are unique.
151        Some(unsafe { UniqueEntityEquivalentArray::from_array_ref_unchecked(chunk) })
152    }
153
154    /// Returns an array reference to the first `N` items in the slice and the remaining slice.
155    ///
156    /// Equivalent to [`[T]::split_first_chunk`](slice::split_first_chunk).
157    pub const fn split_first_chunk<const N: usize>(
158        &self,
159    ) -> Option<(
160        &UniqueEntityEquivalentArray<T, N>,
161        &UniqueEntityEquivalentSlice<T>,
162    )> {
163        let Some((chunk, rest)) = self.0.split_first_chunk() else {
164            return None;
165        };
166        // SAFETY: All elements in the original slice are unique.
167        unsafe {
168            Some((
169                UniqueEntityEquivalentArray::from_array_ref_unchecked(chunk),
170                Self::from_slice_unchecked(rest),
171            ))
172        }
173    }
174
175    /// Returns an array reference to the last `N` items in the slice and the remaining slice.
176    ///
177    /// Equivalent to [`[T]::split_last_chunk`](slice::split_last_chunk).
178    pub const fn split_last_chunk<const N: usize>(
179        &self,
180    ) -> Option<(
181        &UniqueEntityEquivalentSlice<T>,
182        &UniqueEntityEquivalentArray<T, N>,
183    )> {
184        let Some((rest, chunk)) = self.0.split_last_chunk() else {
185            return None;
186        };
187        // SAFETY: All elements in the original slice are unique.
188        unsafe {
189            Some((
190                Self::from_slice_unchecked(rest),
191                UniqueEntityEquivalentArray::from_array_ref_unchecked(chunk),
192            ))
193        }
194    }
195
196    /// Returns an array reference to the last `N` items in the slice.
197    ///
198    /// Equivalent to [`[T]::last_chunk`](slice::last_chunk).
199    pub const fn last_chunk<const N: usize>(&self) -> Option<&UniqueEntityEquivalentArray<T, N>> {
200        let Some(chunk) = self.0.last_chunk() else {
201            return None;
202        };
203        // SAFETY: All elements in the original slice are unique.
204        Some(unsafe { UniqueEntityEquivalentArray::from_array_ref_unchecked(chunk) })
205    }
206
207    /// Returns a reference to a subslice.
208    ///
209    /// Equivalent to the range functionality of [`[T]::get`].
210    ///
211    /// Note that only the inner [`[T]::get`] supports indexing with a [`usize`].
212    ///
213    /// [`[T]::get`]: `slice::get`
214    pub fn get<I>(&self, index: I) -> Option<&Self>
215    where
216        Self: Index<I>,
217        I: SliceIndex<[T], Output = [T]>,
218    {
219        self.0.get(index).map(|slice|
220            // SAFETY: All elements in the original slice are unique.
221            unsafe { Self::from_slice_unchecked(slice) })
222    }
223
224    /// Returns a mutable reference to a subslice.
225    ///
226    /// Equivalent to the range functionality of [`[T]::get_mut`].
227    ///
228    /// Note that `UniqueEntityEquivalentSlice::get_mut` cannot be called with a [`usize`].
229    ///
230    /// [`[T]::get_mut`]: `slice::get_mut`
231    pub fn get_mut<I>(&mut self, index: I) -> Option<&mut Self>
232    where
233        Self: Index<I>,
234        I: SliceIndex<[T], Output = [T]>,
235    {
236        self.0.get_mut(index).map(|slice|
237            // SAFETY: All elements in the original slice are unique.
238            unsafe { Self::from_slice_unchecked_mut(slice) })
239    }
240
241    /// Returns a reference to a subslice, without doing bounds checking.
242    ///
243    /// Equivalent to the range functionality of [`[T]::get_unchecked`].
244    ///
245    /// Note that only the inner [`[T]::get_unchecked`] supports indexing with a [`usize`].
246    ///
247    /// # Safety
248    ///
249    /// `index` must be safe to use with [`[T]::get_unchecked`]
250    ///
251    /// [`[T]::get_unchecked`]: `slice::get_unchecked`
252    pub unsafe fn get_unchecked<I>(&self, index: I) -> &Self
253    where
254        Self: Index<I>,
255        I: SliceIndex<[T], Output = [T]>,
256    {
257        // SAFETY: All elements in the original slice are unique.
258        unsafe { Self::from_slice_unchecked(self.0.get_unchecked(index)) }
259    }
260    /// Returns a mutable reference to a subslice, without doing bounds checking.
261    ///
262    /// Equivalent to the range functionality of [`[T]::get_unchecked_mut`].
263    ///
264    /// Note that `UniqueEntityEquivalentSlice::get_unchecked_mut` cannot be called with an index.
265    ///
266    /// # Safety
267    ///
268    /// `index` must be safe to use with [`[T]::get_unchecked_mut`]
269    ///
270    /// [`[T]::get_unchecked_mut`]: `slice::get_unchecked_mut`
271    pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut Self
272    where
273        Self: Index<I>,
274        I: SliceIndex<[T], Output = [T]>,
275    {
276        // SAFETY: All elements in the original slice are unique.
277        unsafe { Self::from_slice_unchecked_mut(self.0.get_unchecked_mut(index)) }
278    }
279
280    /// Returns an unsafe mutable pointer to the slice's buffer.
281    pub const fn as_mut_ptr(&mut self) -> *mut T {
282        self.0.as_mut_ptr()
283    }
284
285    /// Returns the two unsafe mutable pointers spanning the slice.
286    pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
287        self.0.as_mut_ptr_range()
288    }
289
290    /// Swaps two elements in the slice.
291    pub fn swap(&mut self, a: usize, b: usize) {
292        self.0.swap(a, b);
293    }
294
295    /// Reverses the order of elements in the slice, in place.
296    pub fn reverse(&mut self) {
297        self.0.reverse();
298    }
299
300    /// Returns an iterator over the slice.
301    pub fn iter(&self) -> Iter<'_, T> {
302        // SAFETY: All elements in the original slice are unique.
303        unsafe { UniqueEntityIter::from_iter_unchecked(self.0.iter()) }
304    }
305
306    /// Returns an iterator over all contiguous windows of length
307    /// `size`.
308    ///
309    /// Equivalent to [`[T]::windows`].
310    ///
311    /// [`[T]::windows`]: `slice::windows`
312    pub fn windows(&self, size: usize) -> Windows<'_, T> {
313        // SAFETY: Any subslice of a unique slice is also unique.
314        unsafe { UniqueEntityEquivalentSliceIter::from_slice_iter_unchecked(self.0.windows(size)) }
315    }
316
317    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
318    /// beginning of the slice.
319    ///
320    /// Equivalent to [`[T]::chunks`].
321    ///
322    /// [`[T]::chunks`]: `slice::chunks`
323    pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
324        // SAFETY: Any subslice of a unique slice is also unique.
325        unsafe {
326            UniqueEntityEquivalentSliceIter::from_slice_iter_unchecked(self.0.chunks(chunk_size))
327        }
328    }
329
330    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
331    /// beginning of the slice.
332    ///
333    /// Equivalent to [`[T]::chunks_mut`].
334    ///
335    /// [`[T]::chunks_mut`]: `slice::chunks_mut`
336    pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
337        // SAFETY: Any subslice of a unique slice is also unique.
338        unsafe {
339            UniqueEntityEquivalentSliceIterMut::from_mut_slice_iter_unchecked(
340                self.0.chunks_mut(chunk_size),
341            )
342        }
343    }
344
345    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
346    /// beginning of the slice.
347    ///
348    /// Equivalent to [`[T]::chunks_exact`].
349    ///
350    /// [`[T]::chunks_exact`]: `slice::chunks_exact`
351    pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
352        // SAFETY: Any subslice of a unique slice is also unique.
353        unsafe {
354            UniqueEntityEquivalentSliceIter::from_slice_iter_unchecked(
355                self.0.chunks_exact(chunk_size),
356            )
357        }
358    }
359
360    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
361    /// beginning of the slice.
362    ///
363    /// Equivalent to [`[T]::chunks_exact_mut`].
364    ///
365    /// [`[T]::chunks_exact_mut`]: `slice::chunks_exact_mut`
366    pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
367        // SAFETY: Any subslice of a unique slice is also unique.
368        unsafe {
369            UniqueEntityEquivalentSliceIterMut::from_mut_slice_iter_unchecked(
370                self.0.chunks_exact_mut(chunk_size),
371            )
372        }
373    }
374
375    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
376    /// of the slice.
377    ///
378    /// Equivalent to [`[T]::rchunks`].
379    ///
380    /// [`[T]::rchunks`]: `slice::rchunks`
381    pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
382        // SAFETY: Any subslice of a unique slice is also unique.
383        unsafe {
384            UniqueEntityEquivalentSliceIter::from_slice_iter_unchecked(self.0.rchunks(chunk_size))
385        }
386    }
387
388    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
389    /// of the slice.
390    ///
391    /// Equivalent to [`[T]::rchunks_mut`].
392    ///
393    /// [`[T]::rchunks_mut`]: `slice::rchunks_mut`
394    pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
395        // SAFETY: Any subslice of a unique slice is also unique.
396        unsafe {
397            UniqueEntityEquivalentSliceIterMut::from_mut_slice_iter_unchecked(
398                self.0.rchunks_mut(chunk_size),
399            )
400        }
401    }
402
403    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
404    /// end of the slice.
405    ///
406    /// Equivalent to [`[T]::rchunks_exact`].
407    ///
408    /// [`[T]::rchunks_exact`]: `slice::rchunks_exact`
409    pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
410        // SAFETY: Any subslice of a unique slice is also unique.
411        unsafe {
412            UniqueEntityEquivalentSliceIter::from_slice_iter_unchecked(
413                self.0.rchunks_exact(chunk_size),
414            )
415        }
416    }
417
418    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
419    /// of the slice.
420    ///
421    /// Equivalent to [`[T]::rchunks_exact_mut`].
422    ///
423    /// [`[T]::rchunks_exact_mut`]: `slice::rchunks_exact_mut`
424    pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
425        // SAFETY: Any subslice of a unique slice is also unique.
426        unsafe {
427            UniqueEntityEquivalentSliceIterMut::from_mut_slice_iter_unchecked(
428                self.0.rchunks_exact_mut(chunk_size),
429            )
430        }
431    }
432
433    /// Returns an iterator over the slice producing non-overlapping runs
434    /// of elements using the predicate to separate them.
435    ///
436    /// Equivalent to [`[T]::chunk_by`].
437    ///
438    /// [`[T]::chunk_by`]: `slice::chunk_by`
439    pub fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, F, T>
440    where
441        F: FnMut(&T, &T) -> bool,
442    {
443        // SAFETY: Any subslice of a unique slice is also unique.
444        unsafe { UniqueEntityEquivalentSliceIter::from_slice_iter_unchecked(self.0.chunk_by(pred)) }
445    }
446
447    /// Returns an iterator over the slice producing non-overlapping mutable
448    /// runs of elements using the predicate to separate them.
449    ///
450    /// Equivalent to [`[T]::chunk_by_mut`].
451    ///
452    /// [`[T]::chunk_by_mut`]: `slice::chunk_by_mut`
453    pub fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, F, T>
454    where
455        F: FnMut(&T, &T) -> bool,
456    {
457        // SAFETY: Any subslice of a unique slice is also unique.
458        unsafe {
459            UniqueEntityEquivalentSliceIterMut::from_mut_slice_iter_unchecked(
460                self.0.chunk_by_mut(pred),
461            )
462        }
463    }
464
465    /// Divides one slice into two at an index.
466    ///
467    /// Equivalent to [`[T]::split_at`](slice::split_at).
468    pub const fn split_at(&self, mid: usize) -> (&Self, &Self) {
469        let (left, right) = self.0.split_at(mid);
470        // SAFETY: All elements in the original slice are unique.
471        unsafe {
472            (
473                Self::from_slice_unchecked(left),
474                Self::from_slice_unchecked(right),
475            )
476        }
477    }
478
479    /// Divides one mutable slice into two at an index.
480    ///
481    /// Equivalent to [`[T]::split_at_mut`](slice::split_at_mut).
482    pub const fn split_at_mut(&mut self, mid: usize) -> (&mut Self, &mut Self) {
483        let (left, right) = self.0.split_at_mut(mid);
484        // SAFETY: All elements in the original slice are unique.
485        unsafe {
486            (
487                Self::from_slice_unchecked_mut(left),
488                Self::from_slice_unchecked_mut(right),
489            )
490        }
491    }
492
493    /// Divides one slice into two at an index, without doing bounds checking.
494    ///
495    /// Equivalent to [`[T]::split_at_unchecked`](slice::split_at_unchecked).
496    ///
497    /// # Safety
498    ///
499    /// `mid` must be safe to use in [`[T]::split_at_unchecked`].
500    ///
501    /// [`[T]::split_at_unchecked`]: `slice::split_at_unchecked`
502    pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&Self, &Self) {
503        // SAFETY: The safety contract is upheld by the caller.
504        let (left, right) = unsafe { self.0.split_at_unchecked(mid) };
505        // SAFETY: All elements in the original slice are unique.
506        unsafe {
507            (
508                Self::from_slice_unchecked(left),
509                Self::from_slice_unchecked(right),
510            )
511        }
512    }
513
514    /// Divides one mutable slice into two at an index, without doing bounds checking.
515    ///
516    /// Equivalent to [`[T]::split_at_mut_unchecked`](slice::split_at_mut_unchecked).
517    ///
518    /// # Safety
519    ///
520    /// `mid` must be safe to use in [`[T]::split_at_mut_unchecked`].
521    ///
522    /// [`[T]::split_at_mut_unchecked`]: `slice::split_at_mut_unchecked`
523    pub const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut Self, &mut Self) {
524        // SAFETY: The safety contract is upheld by the caller.
525        let (left, right) = unsafe { self.0.split_at_mut_unchecked(mid) };
526        // SAFETY: All elements in the original slice are unique.
527        unsafe {
528            (
529                Self::from_slice_unchecked_mut(left),
530                Self::from_slice_unchecked_mut(right),
531            )
532        }
533    }
534
535    /// Divides one slice into two at an index, returning `None` if the slice is
536    /// too short.
537    ///
538    /// Equivalent to [`[T]::split_at_checked`](slice::split_at_checked).
539    pub const fn split_at_checked(&self, mid: usize) -> Option<(&Self, &Self)> {
540        let Some((left, right)) = self.0.split_at_checked(mid) else {
541            return None;
542        };
543        // SAFETY: All elements in the original slice are unique.
544        unsafe {
545            Some((
546                Self::from_slice_unchecked(left),
547                Self::from_slice_unchecked(right),
548            ))
549        }
550    }
551
552    /// Divides one mutable slice into two at an index, returning `None` if the
553    /// slice is too short.
554    ///
555    /// Equivalent to [`[T]::split_at_mut_checked`](slice::split_at_mut_checked).
556    pub const fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut Self, &mut Self)> {
557        let Some((left, right)) = self.0.split_at_mut_checked(mid) else {
558            return None;
559        };
560        // SAFETY: All elements in the original slice are unique.
561        unsafe {
562            Some((
563                Self::from_slice_unchecked_mut(left),
564                Self::from_slice_unchecked_mut(right),
565            ))
566        }
567    }
568
569    /// Returns an iterator over subslices separated by elements that match
570    /// `pred`.
571    ///
572    /// Equivalent to [`[T]::split`].
573    ///
574    /// [`[T]::split`]: `slice::split`
575    pub fn split<F>(&self, pred: F) -> Split<'_, F, T>
576    where
577        F: FnMut(&T) -> bool,
578    {
579        // SAFETY: Any subslice of a unique slice is also unique.
580        unsafe { UniqueEntityEquivalentSliceIter::from_slice_iter_unchecked(self.0.split(pred)) }
581    }
582
583    /// Returns an iterator over mutable subslices separated by elements that
584    /// match `pred`.
585    ///
586    /// Equivalent to [`[T]::split_mut`].
587    ///
588    /// [`[T]::split_mut`]: `slice::split_mut`
589    pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, F, T>
590    where
591        F: FnMut(&T) -> bool,
592    {
593        // SAFETY: Any subslice of a unique slice is also unique.
594        unsafe {
595            UniqueEntityEquivalentSliceIterMut::from_mut_slice_iter_unchecked(
596                self.0.split_mut(pred),
597            )
598        }
599    }
600
601    /// Returns an iterator over subslices separated by elements that match
602    /// `pred`.
603    ///
604    /// Equivalent to [`[T]::split_inclusive`].
605    ///
606    /// [`[T]::split_inclusive`]: `slice::split_inclusive`
607    pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, F, T>
608    where
609        F: FnMut(&T) -> bool,
610    {
611        // SAFETY: Any subslice of a unique slice is also unique.
612        unsafe {
613            UniqueEntityEquivalentSliceIter::from_slice_iter_unchecked(self.0.split_inclusive(pred))
614        }
615    }
616
617    /// Returns an iterator over mutable subslices separated by elements that
618    /// match `pred`.
619    ///
620    /// Equivalent to [`[T]::split_inclusive_mut`].
621    ///
622    /// [`[T]::split_inclusive_mut`]: `slice::split_inclusive_mut`
623    pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, F, T>
624    where
625        F: FnMut(&T) -> bool,
626    {
627        // SAFETY: Any subslice of a unique slice is also unique.
628        unsafe {
629            UniqueEntityEquivalentSliceIterMut::from_mut_slice_iter_unchecked(
630                self.0.split_inclusive_mut(pred),
631            )
632        }
633    }
634
635    /// Returns an iterator over subslices separated by elements that match
636    /// `pred`, starting at the end of the slice and working backwards.
637    ///
638    /// Equivalent to [`[T]::rsplit`].
639    ///
640    /// [`[T]::rsplit`]: `slice::rsplit`
641    pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, F, T>
642    where
643        F: FnMut(&T) -> bool,
644    {
645        // SAFETY: Any subslice of a unique slice is also unique.
646        unsafe { UniqueEntityEquivalentSliceIter::from_slice_iter_unchecked(self.0.rsplit(pred)) }
647    }
648
649    /// Returns an iterator over mutable subslices separated by elements that
650    /// match `pred`, starting at the end of the slice and working
651    /// backwards.
652    ///
653    /// Equivalent to [`[T]::rsplit_mut`].
654    ///
655    /// [`[T]::rsplit_mut`]: `slice::rsplit_mut`
656    pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, F, T>
657    where
658        F: FnMut(&T) -> bool,
659    {
660        // SAFETY: Any subslice of a unique slice is also unique.
661        unsafe {
662            UniqueEntityEquivalentSliceIterMut::from_mut_slice_iter_unchecked(
663                self.0.rsplit_mut(pred),
664            )
665        }
666    }
667
668    /// Returns an iterator over subslices separated by elements that match
669    /// `pred`, limited to returning at most `n` items.
670    ///
671    /// Equivalent to [`[T]::splitn`].
672    ///
673    /// [`[T]::splitn`]: `slice::splitn`
674    pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, F, T>
675    where
676        F: FnMut(&T) -> bool,
677    {
678        // SAFETY: Any subslice of a unique slice is also unique.
679        unsafe {
680            UniqueEntityEquivalentSliceIter::from_slice_iter_unchecked(self.0.splitn(n, pred))
681        }
682    }
683
684    /// Returns an iterator over mutable subslices separated by elements that match
685    /// `pred`, limited to returning at most `n` items.
686    ///
687    /// Equivalent to [`[T]::splitn_mut`].
688    ///
689    /// [`[T]::splitn_mut`]: `slice::splitn_mut`
690    pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, F, T>
691    where
692        F: FnMut(&T) -> bool,
693    {
694        // SAFETY: Any subslice of a unique slice is also unique.
695        unsafe {
696            UniqueEntityEquivalentSliceIterMut::from_mut_slice_iter_unchecked(
697                self.0.splitn_mut(n, pred),
698            )
699        }
700    }
701
702    /// Returns an iterator over subslices separated by elements that match
703    /// `pred` limited to returning at most `n` items.
704    ///
705    /// Equivalent to [`[T]::rsplitn`].
706    ///
707    /// [`[T]::rsplitn`]: `slice::rsplitn`
708    pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, F, T>
709    where
710        F: FnMut(&T) -> bool,
711    {
712        // SAFETY: Any subslice of a unique slice is also unique.
713        unsafe {
714            UniqueEntityEquivalentSliceIter::from_slice_iter_unchecked(self.0.rsplitn(n, pred))
715        }
716    }
717
718    /// Returns an iterator over subslices separated by elements that match
719    /// `pred` limited to returning at most `n` items.
720    ///
721    /// Equivalent to [`[T]::rsplitn_mut`].
722    ///
723    /// [`[T]::rsplitn_mut`]: `slice::rsplitn_mut`
724    pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, F, T>
725    where
726        F: FnMut(&T) -> bool,
727    {
728        // SAFETY: Any subslice of a unique slice is also unique.
729        unsafe {
730            UniqueEntityEquivalentSliceIterMut::from_mut_slice_iter_unchecked(
731                self.0.rsplitn_mut(n, pred),
732            )
733        }
734    }
735
736    /// Sorts the slice **without** preserving the initial order of equal elements.
737    ///
738    /// Equivalent to [`[T]::sort_unstable`](slice::sort_unstable).
739    pub fn sort_unstable(&mut self)
740    where
741        T: Ord,
742    {
743        self.0.sort_unstable();
744    }
745
746    /// Sorts the slice with a comparison function, **without** preserving the initial order of
747    /// equal elements.
748    ///
749    /// Equivalent to [`[T]::sort_unstable_by`](slice::sort_unstable_by).
750    pub fn sort_unstable_by<F>(&mut self, compare: F)
751    where
752        F: FnMut(&T, &T) -> Ordering,
753    {
754        self.0.sort_unstable_by(compare);
755    }
756
757    /// Sorts the slice with a key extraction function, **without** preserving the initial order of
758    /// equal elements.
759    ///
760    /// Equivalent to [`[T]::sort_unstable_by_key`](slice::sort_unstable_by_key).
761    pub fn sort_unstable_by_key<K, F>(&mut self, f: F)
762    where
763        F: FnMut(&T) -> K,
764        K: Ord,
765    {
766        self.0.sort_unstable_by_key(f);
767    }
768
769    /// Rotates the slice in-place such that the first `mid` elements of the
770    /// slice move to the end while the last `self.len() - mid` elements move to
771    /// the front.
772    ///
773    /// Equivalent to [`[T]::rotate_left`](slice::rotate_left).
774    pub fn rotate_left(&mut self, mid: usize) {
775        self.0.rotate_left(mid);
776    }
777
778    /// Rotates the slice in-place such that the first `self.len() - k`
779    /// elements of the slice move to the end while the last `k` elements move
780    /// to the front.
781    ///
782    /// Equivalent to [`[T]::rotate_right`](slice::rotate_right).
783    pub fn rotate_right(&mut self, mid: usize) {
784        self.0.rotate_right(mid);
785    }
786
787    /// Sorts the slice, preserving initial order of equal elements.
788    ///
789    /// Equivalent to [`[T]::sort`](slice::sort()).
790    pub fn sort(&mut self)
791    where
792        T: Ord,
793    {
794        self.0.sort();
795    }
796
797    /// Sorts the slice with a comparison function, preserving initial order of equal elements.
798    ///
799    /// Equivalent to [`[T]::sort_by`](slice::sort_by).
800    pub fn sort_by<F>(&mut self, compare: F)
801    where
802        F: FnMut(&T, &T) -> Ordering,
803    {
804        self.0.sort_by(compare);
805    }
806
807    /// Sorts the slice with a key extraction function, preserving initial order of equal elements.
808    ///
809    /// Equivalent to [`[T]::sort_by_key`](slice::sort_by_key).
810    pub fn sort_by_key<K, F>(&mut self, f: F)
811    where
812        F: FnMut(&T) -> K,
813        K: Ord,
814    {
815        self.0.sort_by_key(f);
816    }
817
818    // Sorts the slice with a key extraction function, preserving initial order of equal elements.
819    ///
820    /// Equivalent to [`[T]::sort_by_cached_key`](slice::sort_by_cached_key).
821    pub fn sort_by_cached_key<K, F>(&mut self, f: F)
822    where
823        F: FnMut(&T) -> K,
824        K: Ord,
825    {
826        self.0.sort_by_cached_key(f);
827    }
828
829    /// Copies self into a new `UniqueEntityEquivalentVec`.
830    pub fn to_vec(&self) -> UniqueEntityEquivalentVec<T>
831    where
832        T: Clone,
833    {
834        // SAFETY: All elements in the original slice are unique.
835        unsafe { UniqueEntityEquivalentVec::from_vec_unchecked(self.0.to_vec()) }
836    }
837
838    /// Converts `self` into a vector without clones or allocation.
839    ///
840    /// Equivalent to [`[T]::into_vec`](slice::into_vec).
841    pub fn into_vec(self: Box<Self>) -> UniqueEntityEquivalentVec<T> {
842        // SAFETY:
843        // This matches the implementation of `slice::into_vec`.
844        // All elements in the original slice are unique.
845        unsafe {
846            let len = self.len();
847            let vec = Vec::from_raw_parts(Box::into_raw(self).cast::<T>(), len, len);
848            UniqueEntityEquivalentVec::from_vec_unchecked(vec)
849        }
850    }
851}
852
853/// Converts a reference to T into a slice of length 1 (without copying).
854pub const fn from_ref<T: EntityEquivalent>(s: &T) -> &UniqueEntityEquivalentSlice<T> {
855    // SAFETY: A slice with a length of 1 is always unique.
856    unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(slice::from_ref(s)) }
857}
858
859/// Converts a reference to T into a slice of length 1 (without copying).
860pub const fn from_mut<T: EntityEquivalent>(s: &mut T) -> &mut UniqueEntityEquivalentSlice<T> {
861    // SAFETY: A slice with a length of 1 is always unique.
862    unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(slice::from_mut(s)) }
863}
864
865/// Forms a slice from a pointer and a length.
866///
867/// Equivalent to [`slice::from_raw_parts`].
868///
869/// # Safety
870///
871/// [`slice::from_raw_parts`] must be safe to call with `data` and `len`.
872/// Additionally, all elements in the resulting slice must be unique.
873pub const unsafe fn from_raw_parts<'a, T: EntityEquivalent>(
874    data: *const T,
875    len: usize,
876) -> &'a UniqueEntityEquivalentSlice<T> {
877    // SAFETY: The safety contract is upheld by the caller.
878    unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(slice::from_raw_parts(data, len)) }
879}
880
881/// Performs the same functionality as [`from_raw_parts`], except that a mutable slice is returned.
882///
883/// Equivalent to [`slice::from_raw_parts_mut`].
884///
885/// # Safety
886///
887/// [`slice::from_raw_parts_mut`] must be safe to call with `data` and `len`.
888/// Additionally, all elements in the resulting slice must be unique.
889pub const unsafe fn from_raw_parts_mut<'a, T: EntityEquivalent>(
890    data: *mut T,
891    len: usize,
892) -> &'a mut UniqueEntityEquivalentSlice<T> {
893    // SAFETY: The safety contract is upheld by the caller.
894    unsafe {
895        UniqueEntityEquivalentSlice::from_slice_unchecked_mut(slice::from_raw_parts_mut(data, len))
896    }
897}
898
899/// Casts a slice of entity slices to a slice of [`UniqueEntityEquivalentSlice`]s.
900///
901/// # Safety
902///
903/// All elements in each of the cast slices must be unique.
904pub unsafe fn cast_slice_of_unique_entity_slice<'a, 'b, T: EntityEquivalent + 'a>(
905    slice: &'b [&'a [T]],
906) -> &'b [&'a UniqueEntityEquivalentSlice<T>] {
907    // SAFETY: All elements in the original iterator are unique slices.
908    unsafe { &*(ptr::from_ref(slice) as *const [&UniqueEntityEquivalentSlice<T>]) }
909}
910
911/// Casts a mutable slice of entity slices to a slice of [`UniqueEntityEquivalentSlice`]s.
912///
913/// # Safety
914///
915/// All elements in each of the cast slices must be unique.
916pub unsafe fn cast_slice_of_unique_entity_slice_mut<'a, 'b, T: EntityEquivalent + 'a>(
917    slice: &'b mut [&'a [T]],
918) -> &'b mut [&'a UniqueEntityEquivalentSlice<T>] {
919    // SAFETY: All elements in the original iterator are unique slices.
920    unsafe { &mut *(ptr::from_mut(slice) as *mut [&UniqueEntityEquivalentSlice<T>]) }
921}
922
923/// Casts a mutable slice of mutable entity slices to a slice of mutable [`UniqueEntityEquivalentSlice`]s.
924///
925/// # Safety
926///
927/// All elements in each of the cast slices must be unique.
928pub unsafe fn cast_slice_of_mut_unique_entity_slice_mut<'a, 'b, T: EntityEquivalent + 'a>(
929    slice: &'b mut [&'a mut [T]],
930) -> &'b mut [&'a mut UniqueEntityEquivalentSlice<T>] {
931    // SAFETY: All elements in the original iterator are unique slices.
932    unsafe { &mut *(ptr::from_mut(slice) as *mut [&mut UniqueEntityEquivalentSlice<T>]) }
933}
934
935impl<'a, T: EntityEquivalent> IntoIterator for &'a UniqueEntityEquivalentSlice<T> {
936    type Item = &'a T;
937
938    type IntoIter = Iter<'a, T>;
939
940    fn into_iter(self) -> Self::IntoIter {
941        self.iter()
942    }
943}
944
945impl<'a, T: EntityEquivalent> IntoIterator for &'a Box<UniqueEntityEquivalentSlice<T>> {
946    type Item = &'a T;
947
948    type IntoIter = Iter<'a, T>;
949
950    fn into_iter(self) -> Self::IntoIter {
951        self.iter()
952    }
953}
954
955impl<T: EntityEquivalent> IntoIterator for Box<UniqueEntityEquivalentSlice<T>> {
956    type Item = T;
957
958    type IntoIter = unique_vec::IntoIter<T>;
959
960    fn into_iter(self) -> Self::IntoIter {
961        self.into_vec().into_iter()
962    }
963}
964
965impl<T: EntityEquivalent> Deref for UniqueEntityEquivalentSlice<T> {
966    type Target = [T];
967
968    fn deref(&self) -> &Self::Target {
969        &self.0
970    }
971}
972
973impl<T: EntityEquivalent> AsRef<[T]> for UniqueEntityEquivalentSlice<T> {
974    fn as_ref(&self) -> &[T] {
975        self
976    }
977}
978
979impl<T: EntityEquivalent> AsRef<Self> for UniqueEntityEquivalentSlice<T> {
980    fn as_ref(&self) -> &Self {
981        self
982    }
983}
984
985impl<T: EntityEquivalent> AsMut<Self> for UniqueEntityEquivalentSlice<T> {
986    fn as_mut(&mut self) -> &mut Self {
987        self
988    }
989}
990
991impl<T: EntityEquivalent> Borrow<[T]> for UniqueEntityEquivalentSlice<T> {
992    fn borrow(&self) -> &[T] {
993        self
994    }
995}
996
997impl<T: EntityEquivalent + Clone> Clone for Box<UniqueEntityEquivalentSlice<T>> {
998    fn clone(&self) -> Self {
999        self.to_vec().into_boxed_slice()
1000    }
1001}
1002
1003impl<T: EntityEquivalent> Default for &UniqueEntityEquivalentSlice<T> {
1004    fn default() -> Self {
1005        // SAFETY: All elements in the original slice are unique.
1006        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(Default::default()) }
1007    }
1008}
1009
1010impl<T: EntityEquivalent> Default for &mut UniqueEntityEquivalentSlice<T> {
1011    fn default() -> Self {
1012        // SAFETY: All elements in the original slice are unique.
1013        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(Default::default()) }
1014    }
1015}
1016
1017impl<T: EntityEquivalent> Default for Box<UniqueEntityEquivalentSlice<T>> {
1018    fn default() -> Self {
1019        // SAFETY: All elements in the original slice are unique.
1020        unsafe { UniqueEntityEquivalentSlice::from_boxed_slice_unchecked(Default::default()) }
1021    }
1022}
1023
1024impl<T: EntityEquivalent + Clone> From<&UniqueEntityEquivalentSlice<T>>
1025    for Box<UniqueEntityEquivalentSlice<T>>
1026{
1027    fn from(value: &UniqueEntityEquivalentSlice<T>) -> Self {
1028        // SAFETY: All elements in the original slice are unique.
1029        unsafe { UniqueEntityEquivalentSlice::from_boxed_slice_unchecked(value.0.into()) }
1030    }
1031}
1032
1033impl<T: EntityEquivalent + Clone> From<&UniqueEntityEquivalentSlice<T>>
1034    for Arc<UniqueEntityEquivalentSlice<T>>
1035{
1036    fn from(value: &UniqueEntityEquivalentSlice<T>) -> Self {
1037        // SAFETY: All elements in the original slice are unique.
1038        unsafe { UniqueEntityEquivalentSlice::from_arc_slice_unchecked(value.0.into()) }
1039    }
1040}
1041
1042impl<T: EntityEquivalent + Clone> From<&UniqueEntityEquivalentSlice<T>>
1043    for Rc<UniqueEntityEquivalentSlice<T>>
1044{
1045    fn from(value: &UniqueEntityEquivalentSlice<T>) -> Self {
1046        // SAFETY: All elements in the original slice are unique.
1047        unsafe { UniqueEntityEquivalentSlice::from_rc_slice_unchecked(value.0.into()) }
1048    }
1049}
1050
1051impl<'a, T: EntityEquivalent + Clone> From<&'a UniqueEntityEquivalentSlice<T>>
1052    for Cow<'a, UniqueEntityEquivalentSlice<T>>
1053{
1054    fn from(value: &'a UniqueEntityEquivalentSlice<T>) -> Self {
1055        Cow::Borrowed(value)
1056    }
1057}
1058
1059impl<T: EntityEquivalent + Clone, const N: usize> From<UniqueEntityEquivalentArray<T, N>>
1060    for Box<UniqueEntityEquivalentSlice<T>>
1061{
1062    fn from(value: UniqueEntityEquivalentArray<T, N>) -> Self {
1063        // SAFETY: All elements in the original slice are unique.
1064        unsafe {
1065            UniqueEntityEquivalentSlice::from_boxed_slice_unchecked(Box::new(value.into_inner()))
1066        }
1067    }
1068}
1069
1070impl<'a, T: EntityEquivalent + Clone> From<Cow<'a, UniqueEntityEquivalentSlice<T>>>
1071    for Box<UniqueEntityEquivalentSlice<T>>
1072{
1073    fn from(value: Cow<'a, UniqueEntityEquivalentSlice<T>>) -> Self {
1074        match value {
1075            Cow::Borrowed(slice) => Box::from(slice),
1076            Cow::Owned(slice) => Box::from(slice),
1077        }
1078    }
1079}
1080
1081impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>>
1082    for Box<UniqueEntityEquivalentSlice<T>>
1083{
1084    fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
1085        value.into_boxed_slice()
1086    }
1087}
1088
1089impl<T: EntityEquivalent> FromIterator<T> for Box<UniqueEntityEquivalentSlice<T>> {
1090    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1091        iter.into_iter()
1092            .collect::<UniqueEntityEquivalentVec<T>>()
1093            .into_boxed_slice()
1094    }
1095}
1096
1097impl<T: EntityEquivalent> FromEntitySetIterator<T> for Box<UniqueEntityEquivalentSlice<T>> {
1098    fn from_entity_set_iter<I: EntitySet<Item = T>>(iter: I) -> Self {
1099        iter.into_iter()
1100            .collect_set::<UniqueEntityEquivalentVec<T>>()
1101            .into_boxed_slice()
1102    }
1103}
1104
1105impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
1106    PartialEq<UniqueEntityEquivalentVec<U>> for &UniqueEntityEquivalentSlice<T>
1107{
1108    fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
1109        self.0.eq(other.as_vec())
1110    }
1111}
1112
1113impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
1114    PartialEq<UniqueEntityEquivalentVec<U>> for &mut UniqueEntityEquivalentSlice<T>
1115{
1116    fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
1117        self.0.eq(other.as_vec())
1118    }
1119}
1120
1121impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
1122    PartialEq<UniqueEntityEquivalentVec<U>> for UniqueEntityEquivalentSlice<T>
1123{
1124    fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
1125        self.0.eq(other.as_vec())
1126    }
1127}
1128
1129impl<T: PartialEq<U>, U: EntityEquivalent, const N: usize>
1130    PartialEq<&UniqueEntityEquivalentSlice<U>> for [T; N]
1131{
1132    fn eq(&self, other: &&UniqueEntityEquivalentSlice<U>) -> bool {
1133        self.eq(&other.0)
1134    }
1135}
1136
1137impl<T: PartialEq<U> + Clone, U: EntityEquivalent> PartialEq<&UniqueEntityEquivalentSlice<U>>
1138    for Cow<'_, [T]>
1139{
1140    fn eq(&self, other: &&UniqueEntityEquivalentSlice<U>) -> bool {
1141        self.eq(&&other.0)
1142    }
1143}
1144
1145impl<T: EntityEquivalent + PartialEq<U> + Clone, U: EntityEquivalent>
1146    PartialEq<&UniqueEntityEquivalentSlice<U>> for Cow<'_, UniqueEntityEquivalentSlice<T>>
1147{
1148    fn eq(&self, other: &&UniqueEntityEquivalentSlice<U>) -> bool {
1149        self.0.eq(&other.0)
1150    }
1151}
1152
1153impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<&UniqueEntityEquivalentSlice<U>> for Vec<T> {
1154    fn eq(&self, other: &&UniqueEntityEquivalentSlice<U>) -> bool {
1155        self.eq(&other.0)
1156    }
1157}
1158
1159impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<&UniqueEntityEquivalentSlice<U>>
1160    for VecDeque<T>
1161{
1162    fn eq(&self, other: &&UniqueEntityEquivalentSlice<U>) -> bool {
1163        self.eq(&&other.0)
1164    }
1165}
1166
1167impl<T: PartialEq<U>, U: EntityEquivalent, const N: usize>
1168    PartialEq<&mut UniqueEntityEquivalentSlice<U>> for [T; N]
1169{
1170    fn eq(&self, other: &&mut UniqueEntityEquivalentSlice<U>) -> bool {
1171        self.eq(&other.0)
1172    }
1173}
1174
1175impl<T: PartialEq<U> + Clone, U: EntityEquivalent> PartialEq<&mut UniqueEntityEquivalentSlice<U>>
1176    for Cow<'_, [T]>
1177{
1178    fn eq(&self, other: &&mut UniqueEntityEquivalentSlice<U>) -> bool {
1179        self.eq(&&**other)
1180    }
1181}
1182
1183impl<T: EntityEquivalent + PartialEq<U> + Clone, U: EntityEquivalent>
1184    PartialEq<&mut UniqueEntityEquivalentSlice<U>> for Cow<'_, UniqueEntityEquivalentSlice<T>>
1185{
1186    fn eq(&self, other: &&mut UniqueEntityEquivalentSlice<U>) -> bool {
1187        self.0.eq(&other.0)
1188    }
1189}
1190
1191impl<T: EntityEquivalent + PartialEq<U> + Clone, U: EntityEquivalent>
1192    PartialEq<UniqueEntityEquivalentVec<U>> for Cow<'_, UniqueEntityEquivalentSlice<T>>
1193{
1194    fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
1195        self.0.eq(other.as_vec())
1196    }
1197}
1198
1199impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<&mut UniqueEntityEquivalentSlice<U>>
1200    for Vec<T>
1201{
1202    fn eq(&self, other: &&mut UniqueEntityEquivalentSlice<U>) -> bool {
1203        self.eq(&other.0)
1204    }
1205}
1206
1207impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<&mut UniqueEntityEquivalentSlice<U>>
1208    for VecDeque<T>
1209{
1210    fn eq(&self, other: &&mut UniqueEntityEquivalentSlice<U>) -> bool {
1211        self.eq(&&other.0)
1212    }
1213}
1214
1215impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
1216    PartialEq<UniqueEntityEquivalentSlice<U>> for [T]
1217{
1218    fn eq(&self, other: &UniqueEntityEquivalentSlice<U>) -> bool {
1219        self.eq(&other.0)
1220    }
1221}
1222
1223impl<T: PartialEq<U>, U: EntityEquivalent, const N: usize> PartialEq<UniqueEntityEquivalentSlice<U>>
1224    for [T; N]
1225{
1226    fn eq(&self, other: &UniqueEntityEquivalentSlice<U>) -> bool {
1227        self.eq(&other.0)
1228    }
1229}
1230
1231impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
1232    PartialEq<UniqueEntityEquivalentSlice<U>> for Vec<T>
1233{
1234    fn eq(&self, other: &UniqueEntityEquivalentSlice<U>) -> bool {
1235        self.eq(&other.0)
1236    }
1237}
1238
1239impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<[U; N]>
1240    for &UniqueEntityEquivalentSlice<T>
1241{
1242    fn eq(&self, other: &[U; N]) -> bool {
1243        self.0.eq(other)
1244    }
1245}
1246
1247impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<[U; N]>
1248    for &mut UniqueEntityEquivalentSlice<T>
1249{
1250    fn eq(&self, other: &[U; N]) -> bool {
1251        self.0.eq(other)
1252    }
1253}
1254
1255impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<[U; N]>
1256    for UniqueEntityEquivalentSlice<T>
1257{
1258    fn eq(&self, other: &[U; N]) -> bool {
1259        self.0.eq(other)
1260    }
1261}
1262
1263impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>
1264    PartialEq<UniqueEntityEquivalentArray<U, N>> for &UniqueEntityEquivalentSlice<T>
1265{
1266    fn eq(&self, other: &UniqueEntityEquivalentArray<U, N>) -> bool {
1267        self.0.eq(&other.0)
1268    }
1269}
1270
1271impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>
1272    PartialEq<UniqueEntityEquivalentArray<U, N>> for &mut UniqueEntityEquivalentSlice<T>
1273{
1274    fn eq(&self, other: &UniqueEntityEquivalentArray<U, N>) -> bool {
1275        self.0.eq(&other.0)
1276    }
1277}
1278
1279impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>
1280    PartialEq<UniqueEntityEquivalentArray<U, N>> for UniqueEntityEquivalentSlice<T>
1281{
1282    fn eq(&self, other: &UniqueEntityEquivalentArray<U, N>) -> bool {
1283        self.0.eq(&other.0)
1284    }
1285}
1286
1287impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<Vec<U>> for &UniqueEntityEquivalentSlice<T> {
1288    fn eq(&self, other: &Vec<U>) -> bool {
1289        self.0.eq(other)
1290    }
1291}
1292
1293impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<Vec<U>>
1294    for &mut UniqueEntityEquivalentSlice<T>
1295{
1296    fn eq(&self, other: &Vec<U>) -> bool {
1297        self.0.eq(other)
1298    }
1299}
1300
1301impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<Vec<U>> for UniqueEntityEquivalentSlice<T> {
1302    fn eq(&self, other: &Vec<U>) -> bool {
1303        self.0.eq(other)
1304    }
1305}
1306
1307impl<T: EntityEquivalent + Clone> ToOwned for UniqueEntityEquivalentSlice<T> {
1308    type Owned = UniqueEntityEquivalentVec<T>;
1309
1310    fn to_owned(&self) -> Self::Owned {
1311        // SAFETY: All elements in the original slice are unique.
1312        unsafe { UniqueEntityEquivalentVec::from_vec_unchecked(self.0.to_owned()) }
1313    }
1314}
1315
1316impl<'a, T: EntityEquivalent + Copy, const N: usize> TryFrom<&'a UniqueEntityEquivalentSlice<T>>
1317    for &'a UniqueEntityEquivalentArray<T, N>
1318{
1319    type Error = TryFromSliceError;
1320
1321    fn try_from(value: &'a UniqueEntityEquivalentSlice<T>) -> Result<Self, Self::Error> {
1322        <&[T; N]>::try_from(&value.0).map(|array|
1323                // SAFETY: All elements in the original slice are unique.
1324                unsafe { UniqueEntityEquivalentArray::from_array_ref_unchecked(array) })
1325    }
1326}
1327
1328impl<T: EntityEquivalent + Copy, const N: usize> TryFrom<&UniqueEntityEquivalentSlice<T>>
1329    for UniqueEntityEquivalentArray<T, N>
1330{
1331    type Error = TryFromSliceError;
1332
1333    fn try_from(value: &UniqueEntityEquivalentSlice<T>) -> Result<Self, Self::Error> {
1334        <&Self>::try_from(value).copied()
1335    }
1336}
1337
1338impl<T: EntityEquivalent + Copy, const N: usize> TryFrom<&mut UniqueEntityEquivalentSlice<T>>
1339    for UniqueEntityEquivalentArray<T, N>
1340{
1341    type Error = TryFromSliceError;
1342
1343    fn try_from(value: &mut UniqueEntityEquivalentSlice<T>) -> Result<Self, Self::Error> {
1344        <Self>::try_from(&*value)
1345    }
1346}
1347
1348impl<T: EntityEquivalent> Index<(Bound<usize>, Bound<usize>)> for UniqueEntityEquivalentSlice<T> {
1349    type Output = Self;
1350
1351    fn index(&self, key: (Bound<usize>, Bound<usize>)) -> &Self {
1352        // SAFETY: All elements in the original slice are unique.
1353        unsafe { Self::from_slice_unchecked(self.0.index(key)) }
1354    }
1355}
1356
1357impl<T: EntityEquivalent> Index<Range<usize>> for UniqueEntityEquivalentSlice<T> {
1358    type Output = Self;
1359
1360    fn index(&self, key: Range<usize>) -> &Self {
1361        // SAFETY: All elements in the original slice are unique.
1362        unsafe { Self::from_slice_unchecked(self.0.index(key)) }
1363    }
1364}
1365
1366impl<T: EntityEquivalent> Index<RangeFrom<usize>> for UniqueEntityEquivalentSlice<T> {
1367    type Output = Self;
1368
1369    fn index(&self, key: RangeFrom<usize>) -> &Self {
1370        // SAFETY: All elements in the original slice are unique.
1371        unsafe { Self::from_slice_unchecked(self.0.index(key)) }
1372    }
1373}
1374
1375impl<T: EntityEquivalent> Index<RangeFull> for UniqueEntityEquivalentSlice<T> {
1376    type Output = Self;
1377
1378    fn index(&self, key: RangeFull) -> &Self {
1379        // SAFETY: All elements in the original slice are unique.
1380        unsafe { Self::from_slice_unchecked(self.0.index(key)) }
1381    }
1382}
1383
1384impl<T: EntityEquivalent> Index<RangeInclusive<usize>> for UniqueEntityEquivalentSlice<T> {
1385    type Output = UniqueEntityEquivalentSlice<T>;
1386
1387    fn index(&self, key: RangeInclusive<usize>) -> &Self {
1388        // SAFETY: All elements in the original slice are unique.
1389        unsafe { Self::from_slice_unchecked(self.0.index(key)) }
1390    }
1391}
1392
1393impl<T: EntityEquivalent> Index<RangeTo<usize>> for UniqueEntityEquivalentSlice<T> {
1394    type Output = UniqueEntityEquivalentSlice<T>;
1395
1396    fn index(&self, key: RangeTo<usize>) -> &Self {
1397        // SAFETY: All elements in the original slice are unique.
1398        unsafe { Self::from_slice_unchecked(self.0.index(key)) }
1399    }
1400}
1401
1402impl<T: EntityEquivalent> Index<RangeToInclusive<usize>> for UniqueEntityEquivalentSlice<T> {
1403    type Output = UniqueEntityEquivalentSlice<T>;
1404
1405    fn index(&self, key: RangeToInclusive<usize>) -> &Self {
1406        // SAFETY: All elements in the original slice are unique.
1407        unsafe { Self::from_slice_unchecked(self.0.index(key)) }
1408    }
1409}
1410
1411impl<T: EntityEquivalent> Index<usize> for UniqueEntityEquivalentSlice<T> {
1412    type Output = T;
1413
1414    fn index(&self, index: usize) -> &T {
1415        &self.0[index]
1416    }
1417}
1418
1419impl<T: EntityEquivalent> IndexMut<(Bound<usize>, Bound<usize>)>
1420    for UniqueEntityEquivalentSlice<T>
1421{
1422    fn index_mut(&mut self, key: (Bound<usize>, Bound<usize>)) -> &mut Self {
1423        // SAFETY: All elements in the original slice are unique.
1424        unsafe { Self::from_slice_unchecked_mut(self.0.index_mut(key)) }
1425    }
1426}
1427
1428impl<T: EntityEquivalent> IndexMut<Range<usize>> for UniqueEntityEquivalentSlice<T> {
1429    fn index_mut(&mut self, key: Range<usize>) -> &mut Self {
1430        // SAFETY: All elements in the original slice are unique.
1431        unsafe { Self::from_slice_unchecked_mut(self.0.index_mut(key)) }
1432    }
1433}
1434
1435impl<T: EntityEquivalent> IndexMut<RangeFrom<usize>> for UniqueEntityEquivalentSlice<T> {
1436    fn index_mut(&mut self, key: RangeFrom<usize>) -> &mut Self {
1437        // SAFETY: All elements in the original slice are unique.
1438        unsafe { Self::from_slice_unchecked_mut(self.0.index_mut(key)) }
1439    }
1440}
1441
1442impl<T: EntityEquivalent> IndexMut<RangeFull> for UniqueEntityEquivalentSlice<T> {
1443    fn index_mut(&mut self, key: RangeFull) -> &mut Self {
1444        // SAFETY: All elements in the original slice are unique.
1445        unsafe { Self::from_slice_unchecked_mut(self.0.index_mut(key)) }
1446    }
1447}
1448
1449impl<T: EntityEquivalent> IndexMut<RangeInclusive<usize>> for UniqueEntityEquivalentSlice<T> {
1450    fn index_mut(&mut self, key: RangeInclusive<usize>) -> &mut Self {
1451        // SAFETY: All elements in the original slice are unique.
1452        unsafe { Self::from_slice_unchecked_mut(self.0.index_mut(key)) }
1453    }
1454}
1455
1456impl<T: EntityEquivalent> IndexMut<RangeTo<usize>> for UniqueEntityEquivalentSlice<T> {
1457    fn index_mut(&mut self, key: RangeTo<usize>) -> &mut Self {
1458        // SAFETY: All elements in the original slice are unique.
1459        unsafe { Self::from_slice_unchecked_mut(self.0.index_mut(key)) }
1460    }
1461}
1462
1463impl<T: EntityEquivalent> IndexMut<RangeToInclusive<usize>> for UniqueEntityEquivalentSlice<T> {
1464    fn index_mut(&mut self, key: RangeToInclusive<usize>) -> &mut Self {
1465        // SAFETY: All elements in the original slice are unique.
1466        unsafe { Self::from_slice_unchecked_mut(self.0.index_mut(key)) }
1467    }
1468}
1469
1470/// Immutable slice iterator.
1471///
1472/// This struct is created by [`iter`] method on [`UniqueEntityEquivalentSlice`] and
1473/// the [`IntoIterator`] impls on it and [`UniqueEntityEquivalentVec`].
1474///
1475/// [`iter`]: `UniqueEntityEquivalentSlice::iter`
1476pub type Iter<'a, T> = UniqueEntityIter<slice::Iter<'a, T>>;
1477
1478impl<'a, T: EntityEquivalent> UniqueEntityIter<slice::Iter<'a, T>> {
1479    /// Views the underlying data as a subslice of the original data.
1480    ///
1481    /// Equivalent to [`slice::Iter::as_slice`].
1482    pub fn as_slice(&self) -> &'a UniqueEntityEquivalentSlice<T> {
1483        // SAFETY: All elements in the original slice are unique.
1484        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.as_inner().as_slice()) }
1485    }
1486}
1487
1488/// Mutable slice iterator.
1489pub type IterMut<'a, T> = UniqueEntityIter<slice::IterMut<'a, T>>;
1490
1491impl<'a, T: EntityEquivalent> UniqueEntityIter<slice::IterMut<'a, T>> {
1492    /// Views the underlying data as a mutable subslice of the original data.
1493    ///
1494    /// Equivalent to [`slice::IterMut::into_slice`].
1495    pub fn into_slice(self) -> &'a mut UniqueEntityEquivalentSlice<T> {
1496        // SAFETY: All elements in the original slice are unique.
1497        unsafe {
1498            UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.into_inner().into_slice())
1499        }
1500    }
1501
1502    /// Views the underlying data as a subslice of the original data.
1503    ///
1504    /// Equivalent to [`slice::IterMut::as_slice`].
1505    pub fn as_slice(&self) -> &UniqueEntityEquivalentSlice<T> {
1506        // SAFETY: All elements in the original slice are unique.
1507        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.as_inner().as_slice()) }
1508    }
1509}
1510
1511/// An iterator that yields `&UniqueEntityEquivalentSlice`. Note that an entity may appear
1512/// in multiple slices, depending on the wrapped iterator.
1513#[repr(transparent)]
1514#[derive(Debug)]
1515pub struct UniqueEntityEquivalentSliceIter<
1516    'a,
1517    T: EntityEquivalent + 'a,
1518    I: Iterator<Item = &'a [T]>,
1519> {
1520    iter: I,
1521}
1522
1523impl<'a, T: EntityEquivalent + 'a, I: Iterator<Item = &'a [T]>>
1524    UniqueEntityEquivalentSliceIter<'a, T, I>
1525{
1526    /// Constructs a [`UniqueEntityEquivalentSliceIter`] from a slice iterator unsafely.
1527    ///
1528    /// # Safety
1529    ///
1530    /// All elements in each of the slices must be unique.
1531    pub const unsafe fn from_slice_iter_unchecked(iter: I) -> Self {
1532        Self { iter }
1533    }
1534
1535    /// Returns the inner `I`.
1536    pub fn into_inner(self) -> I {
1537        self.iter
1538    }
1539
1540    /// Returns a reference to the inner `I`.
1541    pub const fn as_inner(&self) -> &I {
1542        &self.iter
1543    }
1544
1545    /// Returns a mutable reference to the inner `I`.
1546    ///
1547    /// # Safety
1548    ///
1549    /// `self` must always contain an iterator that yields unique elements,
1550    /// even while this reference is live.
1551    pub const unsafe fn as_mut_inner(&mut self) -> &mut I {
1552        &mut self.iter
1553    }
1554}
1555
1556impl<'a, T: EntityEquivalent + 'a, I: Iterator<Item = &'a [T]>> Iterator
1557    for UniqueEntityEquivalentSliceIter<'a, T, I>
1558{
1559    type Item = &'a UniqueEntityEquivalentSlice<T>;
1560
1561    fn next(&mut self) -> Option<Self::Item> {
1562        self.iter.next().map(|slice|
1563        // SAFETY: All elements in the original iterator are unique slices.
1564        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(slice) })
1565    }
1566
1567    fn size_hint(&self) -> (usize, Option<usize>) {
1568        self.iter.size_hint()
1569    }
1570}
1571
1572impl<'a, T: EntityEquivalent + 'a, I: ExactSizeIterator<Item = &'a [T]>> ExactSizeIterator
1573    for UniqueEntityEquivalentSliceIter<'a, T, I>
1574{
1575}
1576
1577impl<'a, T: EntityEquivalent + 'a, I: DoubleEndedIterator<Item = &'a [T]>> DoubleEndedIterator
1578    for UniqueEntityEquivalentSliceIter<'a, T, I>
1579{
1580    fn next_back(&mut self) -> Option<Self::Item> {
1581        self.iter.next_back().map(|slice|
1582            // SAFETY: All elements in the original iterator are unique slices.
1583            unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(slice) })
1584    }
1585}
1586
1587impl<'a, T: EntityEquivalent + 'a, I: FusedIterator<Item = &'a [T]>> FusedIterator
1588    for UniqueEntityEquivalentSliceIter<'a, T, I>
1589{
1590}
1591
1592impl<'a, T: EntityEquivalent + 'a, I: Iterator<Item = &'a [T]> + AsRef<[&'a [T]]>>
1593    AsRef<[&'a UniqueEntityEquivalentSlice<T>]> for UniqueEntityEquivalentSliceIter<'a, T, I>
1594{
1595    fn as_ref(&self) -> &[&'a UniqueEntityEquivalentSlice<T>] {
1596        // SAFETY:
1597        unsafe { cast_slice_of_unique_entity_slice(self.iter.as_ref()) }
1598    }
1599}
1600
1601/// An iterator over overlapping subslices of length `size`.
1602///
1603/// This struct is created by [`UniqueEntityEquivalentSlice::windows`].
1604pub type Windows<'a, T = Entity> = UniqueEntityEquivalentSliceIter<'a, T, slice::Windows<'a, T>>;
1605
1606/// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1607/// time), starting at the beginning of the slice.
1608///
1609/// This struct is created by [`UniqueEntityEquivalentSlice::chunks`].
1610pub type Chunks<'a, T = Entity> = UniqueEntityEquivalentSliceIter<'a, T, slice::Chunks<'a, T>>;
1611
1612/// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1613/// time), starting at the beginning of the slice.
1614///
1615/// This struct is created by [`UniqueEntityEquivalentSlice::chunks_exact`].
1616pub type ChunksExact<'a, T = Entity> =
1617    UniqueEntityEquivalentSliceIter<'a, T, slice::ChunksExact<'a, T>>;
1618
1619impl<'a, T: EntityEquivalent> UniqueEntityEquivalentSliceIter<'a, T, slice::ChunksExact<'a, T>> {
1620    /// Returns the remainder of the original slice that is not going to be
1621    /// returned by the iterator.
1622    ///
1623    /// Equivalent to [`slice::ChunksExact::remainder`].
1624    pub fn remainder(&self) -> &'a UniqueEntityEquivalentSlice<T> {
1625        // SAFETY: All elements in the original iterator are unique slices.
1626        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.iter.remainder()) }
1627    }
1628}
1629
1630/// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1631/// time), starting at the end of the slice.
1632///
1633/// This struct is created by [`UniqueEntityEquivalentSlice::rchunks`].
1634pub type RChunks<'a, T = Entity> = UniqueEntityEquivalentSliceIter<'a, T, slice::RChunks<'a, T>>;
1635
1636/// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1637/// time), starting at the end of the slice.
1638///
1639/// This struct is created by [`UniqueEntityEquivalentSlice::rchunks_exact`].
1640pub type RChunksExact<'a, T = Entity> =
1641    UniqueEntityEquivalentSliceIter<'a, T, slice::RChunksExact<'a, T>>;
1642
1643impl<'a, T: EntityEquivalent> UniqueEntityEquivalentSliceIter<'a, T, slice::RChunksExact<'a, T>> {
1644    /// Returns the remainder of the original slice that is not going to be
1645    /// returned by the iterator.
1646    ///
1647    /// Equivalent to [`slice::RChunksExact::remainder`].
1648    pub fn remainder(&self) -> &'a UniqueEntityEquivalentSlice<T> {
1649        // SAFETY: All elements in the original iterator are unique slices.
1650        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.iter.remainder()) }
1651    }
1652}
1653
1654/// An iterator over slice in (non-overlapping) chunks separated by a predicate.
1655///
1656/// This struct is created by [`UniqueEntityEquivalentSlice::chunk_by`].
1657pub type ChunkBy<'a, P, T = Entity> =
1658    UniqueEntityEquivalentSliceIter<'a, T, slice::ChunkBy<'a, T, P>>;
1659
1660/// An iterator over subslices separated by elements that match a predicate
1661/// function.
1662///
1663/// This struct is created by [`UniqueEntityEquivalentSlice::split`].
1664pub type Split<'a, P, T = Entity> = UniqueEntityEquivalentSliceIter<'a, T, slice::Split<'a, T, P>>;
1665
1666/// An iterator over subslices separated by elements that match a predicate
1667/// function.
1668///
1669/// This struct is created by [`UniqueEntityEquivalentSlice::split_inclusive`].
1670pub type SplitInclusive<'a, P, T = Entity> =
1671    UniqueEntityEquivalentSliceIter<'a, T, slice::SplitInclusive<'a, T, P>>;
1672
1673/// An iterator over subslices separated by elements that match a predicate
1674/// function, starting from the end of the slice.
1675///
1676/// This struct is created by [`UniqueEntityEquivalentSlice::rsplit`].
1677pub type RSplit<'a, P, T = Entity> =
1678    UniqueEntityEquivalentSliceIter<'a, T, slice::RSplit<'a, T, P>>;
1679
1680/// An iterator over subslices separated by elements that match a predicate
1681/// function, limited to a given number of splits.
1682///
1683/// This struct is created by [`UniqueEntityEquivalentSlice::splitn`].
1684pub type SplitN<'a, P, T = Entity> =
1685    UniqueEntityEquivalentSliceIter<'a, T, slice::SplitN<'a, T, P>>;
1686
1687/// An iterator over subslices separated by elements that match a
1688/// predicate function, limited to a given number of splits, starting
1689/// from the end of the slice.
1690///
1691/// This struct is created by [`UniqueEntityEquivalentSlice::rsplitn`].
1692pub type RSplitN<'a, P, T = Entity> =
1693    UniqueEntityEquivalentSliceIter<'a, T, slice::RSplitN<'a, T, P>>;
1694
1695/// An iterator that yields `&mut UniqueEntityEquivalentSlice`. Note that an entity may appear
1696/// in multiple slices, depending on the wrapped iterator.
1697#[repr(transparent)]
1698#[derive(Debug)]
1699pub struct UniqueEntityEquivalentSliceIterMut<
1700    'a,
1701    T: EntityEquivalent + 'a,
1702    I: Iterator<Item = &'a mut [T]>,
1703> {
1704    iter: I,
1705}
1706
1707impl<'a, T: EntityEquivalent + 'a, I: Iterator<Item = &'a mut [T]>>
1708    UniqueEntityEquivalentSliceIterMut<'a, T, I>
1709{
1710    /// Constructs a [`UniqueEntityEquivalentSliceIterMut`] from a mutable slice iterator unsafely.
1711    ///
1712    /// # Safety
1713    ///
1714    /// All elements in each of the slices must be unique.
1715    pub const unsafe fn from_mut_slice_iter_unchecked(iter: I) -> Self {
1716        Self { iter }
1717    }
1718
1719    /// Returns the inner `I`.
1720    pub fn into_inner(self) -> I {
1721        self.iter
1722    }
1723
1724    /// Returns a reference to the inner `I`.
1725    pub const fn as_inner(&self) -> &I {
1726        &self.iter
1727    }
1728
1729    /// Returns a mutable reference to the inner `I`.
1730    ///
1731    /// # Safety
1732    ///
1733    /// `self` must always contain an iterator that yields unique elements,
1734    /// even while this reference is live.
1735    pub const unsafe fn as_mut_inner(&mut self) -> &mut I {
1736        &mut self.iter
1737    }
1738}
1739
1740impl<'a, T: EntityEquivalent + 'a, I: Iterator<Item = &'a mut [T]>> Iterator
1741    for UniqueEntityEquivalentSliceIterMut<'a, T, I>
1742{
1743    type Item = &'a mut UniqueEntityEquivalentSlice<T>;
1744
1745    fn next(&mut self) -> Option<Self::Item> {
1746        self.iter.next().map(|slice|
1747            // SAFETY: All elements in the original iterator are unique slices.
1748            unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(slice) })
1749    }
1750
1751    fn size_hint(&self) -> (usize, Option<usize>) {
1752        self.iter.size_hint()
1753    }
1754}
1755
1756impl<'a, T: EntityEquivalent + 'a, I: ExactSizeIterator<Item = &'a mut [T]>> ExactSizeIterator
1757    for UniqueEntityEquivalentSliceIterMut<'a, T, I>
1758{
1759}
1760
1761impl<'a, T: EntityEquivalent + 'a, I: DoubleEndedIterator<Item = &'a mut [T]>> DoubleEndedIterator
1762    for UniqueEntityEquivalentSliceIterMut<'a, T, I>
1763{
1764    fn next_back(&mut self) -> Option<Self::Item> {
1765        self.iter.next_back().map(|slice|
1766            // SAFETY: All elements in the original iterator are unique slices.
1767            unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(slice) })
1768    }
1769}
1770
1771impl<'a, T: EntityEquivalent + 'a, I: FusedIterator<Item = &'a mut [T]>> FusedIterator
1772    for UniqueEntityEquivalentSliceIterMut<'a, T, I>
1773{
1774}
1775
1776impl<'a, T: EntityEquivalent + 'a, I: Iterator<Item = &'a mut [T]> + AsRef<[&'a [T]]>>
1777    AsRef<[&'a UniqueEntityEquivalentSlice<T>]> for UniqueEntityEquivalentSliceIterMut<'a, T, I>
1778{
1779    fn as_ref(&self) -> &[&'a UniqueEntityEquivalentSlice<T>] {
1780        // SAFETY: All elements in the original iterator are unique slices.
1781        unsafe { cast_slice_of_unique_entity_slice(self.iter.as_ref()) }
1782    }
1783}
1784
1785impl<'a, T: EntityEquivalent + 'a, I: Iterator<Item = &'a mut [T]> + AsMut<[&'a mut [T]]>>
1786    AsMut<[&'a mut UniqueEntityEquivalentSlice<T>]>
1787    for UniqueEntityEquivalentSliceIterMut<'a, T, I>
1788{
1789    fn as_mut(&mut self) -> &mut [&'a mut UniqueEntityEquivalentSlice<T>] {
1790        // SAFETY: All elements in the original iterator are unique slices.
1791        unsafe { cast_slice_of_mut_unique_entity_slice_mut(self.iter.as_mut()) }
1792    }
1793}
1794
1795/// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1796/// elements at a time), starting at the beginning of the slice.
1797///
1798/// This struct is created by [`UniqueEntityEquivalentSlice::chunks_mut`].
1799pub type ChunksMut<'a, T = Entity> =
1800    UniqueEntityEquivalentSliceIterMut<'a, T, slice::ChunksMut<'a, T>>;
1801
1802/// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1803/// elements at a time), starting at the beginning of the slice.
1804///
1805/// This struct is created by [`UniqueEntityEquivalentSlice::chunks_exact_mut`].
1806pub type ChunksExactMut<'a, T = Entity> =
1807    UniqueEntityEquivalentSliceIterMut<'a, T, slice::ChunksExactMut<'a, T>>;
1808
1809impl<'a, T: EntityEquivalent>
1810    UniqueEntityEquivalentSliceIterMut<'a, T, slice::ChunksExactMut<'a, T>>
1811{
1812    /// Returns the remainder of the original slice that is not going to be
1813    /// returned by the iterator.
1814    ///
1815    /// Equivalent to [`slice::ChunksExactMut::into_remainder`].
1816    pub fn into_remainder(self) -> &'a mut UniqueEntityEquivalentSlice<T> {
1817        // SAFETY: All elements in the original iterator are unique slices.
1818        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.iter.into_remainder()) }
1819    }
1820}
1821
1822/// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1823/// elements at a time), starting at the end of the slice.
1824///
1825/// This struct is created by [`UniqueEntityEquivalentSlice::rchunks_mut`].
1826pub type RChunksMut<'a, T = Entity> =
1827    UniqueEntityEquivalentSliceIterMut<'a, T, slice::RChunksMut<'a, T>>;
1828
1829/// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1830/// elements at a time), starting at the end of the slice.
1831///
1832/// This struct is created by [`UniqueEntityEquivalentSlice::rchunks_exact_mut`].
1833pub type RChunksExactMut<'a, T = Entity> =
1834    UniqueEntityEquivalentSliceIterMut<'a, T, slice::RChunksExactMut<'a, T>>;
1835
1836impl<'a, T: EntityEquivalent>
1837    UniqueEntityEquivalentSliceIterMut<'a, T, slice::RChunksExactMut<'a, T>>
1838{
1839    /// Returns the remainder of the original slice that is not going to be
1840    /// returned by the iterator.
1841    ///
1842    /// Equivalent to [`slice::RChunksExactMut::into_remainder`].
1843    pub fn into_remainder(self) -> &'a mut UniqueEntityEquivalentSlice<T> {
1844        // SAFETY: All elements in the original iterator are unique slices.
1845        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.iter.into_remainder()) }
1846    }
1847}
1848
1849/// An iterator over slice in (non-overlapping) mutable chunks separated
1850/// by a predicate.
1851///
1852/// This struct is created by [`UniqueEntityEquivalentSlice::chunk_by_mut`].
1853pub type ChunkByMut<'a, P, T = Entity> =
1854    UniqueEntityEquivalentSliceIterMut<'a, T, slice::ChunkByMut<'a, T, P>>;
1855
1856/// An iterator over the mutable subslices of the vector which are separated
1857/// by elements that match `pred`.
1858///
1859/// This struct is created by [`UniqueEntityEquivalentSlice::split_mut`].
1860pub type SplitMut<'a, P, T = Entity> =
1861    UniqueEntityEquivalentSliceIterMut<'a, T, slice::SplitMut<'a, T, P>>;
1862
1863/// An iterator over the mutable subslices of the vector which are separated
1864/// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
1865/// parts in the ends of the subslices.
1866///
1867/// This struct is created by [`UniqueEntityEquivalentSlice::split_inclusive_mut`].
1868pub type SplitInclusiveMut<'a, P, T = Entity> =
1869    UniqueEntityEquivalentSliceIterMut<'a, T, slice::SplitInclusiveMut<'a, T, P>>;
1870
1871/// An iterator over the subslices of the vector which are separated
1872/// by elements that match `pred`, starting from the end of the slice.
1873///
1874/// This struct is created by [`UniqueEntityEquivalentSlice::rsplit_mut`].
1875pub type RSplitMut<'a, P, T = Entity> =
1876    UniqueEntityEquivalentSliceIterMut<'a, T, slice::RSplitMut<'a, T, P>>;
1877
1878/// An iterator over subslices separated by elements that match a predicate
1879/// function, limited to a given number of splits.
1880///
1881/// This struct is created by [`UniqueEntityEquivalentSlice::splitn_mut`].
1882pub type SplitNMut<'a, P, T = Entity> =
1883    UniqueEntityEquivalentSliceIterMut<'a, T, slice::SplitNMut<'a, T, P>>;
1884
1885/// An iterator over subslices separated by elements that match a
1886/// predicate function, limited to a given number of splits, starting
1887/// from the end of the slice.
1888///
1889/// This struct is created by [`UniqueEntityEquivalentSlice::rsplitn_mut`].
1890pub type RSplitNMut<'a, P, T = Entity> =
1891    UniqueEntityEquivalentSliceIterMut<'a, T, slice::RSplitNMut<'a, T, P>>;