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