bevy_ecs/entity/
unique_vec.rs

1//! A wrapper around entity [`Vec`]s with a uniqueness invariant.
2
3use core::{
4    borrow::{Borrow, BorrowMut},
5    mem::MaybeUninit,
6    ops::{
7        Bound, Deref, DerefMut, Index, IndexMut, Range, RangeBounds, RangeFrom, RangeFull,
8        RangeInclusive, RangeTo, RangeToInclusive,
9    },
10};
11
12use alloc::{
13    borrow::{Cow, ToOwned},
14    boxed::Box,
15    collections::{BTreeSet, BinaryHeap, TryReserveError, VecDeque},
16    rc::Rc,
17    vec::{self, Vec},
18};
19
20use bevy_platform::sync::Arc;
21
22use super::{
23    unique_slice::{self, UniqueEntityEquivalentSlice},
24    Entity, EntityEquivalent, EntitySet, FromEntitySetIterator, UniqueEntityEquivalentArray,
25    UniqueEntityIter,
26};
27
28/// A `Vec` that contains only unique entities.
29///
30/// "Unique" means that `x != y` holds for any 2 entities in this collection.
31/// This is always true when less than 2 entities are present.
32///
33/// This type is best obtained by its `FromEntitySetIterator` impl, via either
34/// `EntityIterator::collect_set` or `UniqueEntityEquivalentVec::from_entity_iter`.
35///
36/// While this type can be constructed via `Iterator::collect`, doing so is inefficient,
37/// and not recommended.
38///
39/// When `T` is [`Entity`], use the [`UniqueEntityVec`] alias.
40#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
41pub struct UniqueEntityEquivalentVec<T: EntityEquivalent>(Vec<T>);
42
43/// A `Vec` that contains only unique [`Entity`].
44///
45/// This is the default case of a [`UniqueEntityEquivalentVec`].
46pub type UniqueEntityVec = UniqueEntityEquivalentVec<Entity>;
47
48impl<T: EntityEquivalent> UniqueEntityEquivalentVec<T> {
49    /// Constructs a new, empty `UniqueEntityEquivalentVec<T>`.
50    ///
51    /// Equivalent to [`Vec::new`].
52    pub const fn new() -> Self {
53        Self(Vec::new())
54    }
55
56    /// Constructs a new, empty `UniqueEntityEquivalentVec<T>` with at least the specified capacity.
57    ///
58    /// Equivalent to [`Vec::with_capacity`]
59    pub fn with_capacity(capacity: usize) -> Self {
60        Self(Vec::with_capacity(capacity))
61    }
62
63    /// Creates a `UniqueEntityEquivalentVec<T>` directly from a pointer, a length, and a capacity.
64    ///
65    /// Equivalent to [`Vec::from_raw_parts`].
66    ///
67    /// # Safety
68    ///
69    /// It must be safe to call [`Vec::from_raw_parts`] with these inputs,
70    /// and the resulting [`Vec`] must only contain unique elements.
71    pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
72        // SAFETY: Caller ensures it's safe to call `Vec::from_raw_parts`
73        Self(unsafe { Vec::from_raw_parts(ptr, length, capacity) })
74    }
75
76    /// Constructs a `UniqueEntityEquivalentVec` from a [`Vec<T>`] unsafely.
77    ///
78    /// # Safety
79    ///
80    /// `vec` must contain only unique elements.
81    pub unsafe fn from_vec_unchecked(vec: Vec<T>) -> Self {
82        Self(vec)
83    }
84
85    /// Returns the inner [`Vec<T>`].
86    pub fn into_inner(self) -> Vec<T> {
87        self.0
88    }
89
90    /// Returns a reference to the inner [`Vec<T>`].
91    pub fn as_vec(&self) -> &Vec<T> {
92        &self.0
93    }
94
95    /// Returns a mutable reference to the inner [`Vec<T>`].
96    ///
97    /// # Safety
98    ///
99    /// The elements of this `Vec` must always remain unique, even while
100    /// this mutable reference is live.
101    pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<T> {
102        &mut self.0
103    }
104
105    /// Returns the total number of elements the vector can hold without
106    /// reallocating.
107    ///
108    /// Equivalent to [`Vec::capacity`].
109    pub fn capacity(&self) -> usize {
110        self.0.capacity()
111    }
112
113    /// Reserves capacity for at least `additional` more elements to be inserted
114    /// in the given `Vec<T>`.
115    ///
116    /// Equivalent to [`Vec::reserve`].
117    pub fn reserve(&mut self, additional: usize) {
118        self.0.reserve(additional);
119    }
120
121    /// Reserves the minimum capacity for at least `additional` more elements to
122    /// be inserted in the given `UniqueEntityEquivalentVec<T>`.
123    ///
124    /// Equivalent to [`Vec::reserve_exact`].
125    pub fn reserve_exact(&mut self, additional: usize) {
126        self.0.reserve_exact(additional);
127    }
128
129    /// Tries to reserve capacity for at least `additional` more elements to be inserted
130    /// in the given `Vec<T>`.
131    ///
132    /// Equivalent to [`Vec::try_reserve`].
133    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
134        self.0.try_reserve(additional)
135    }
136
137    /// Tries to reserve the minimum capacity for at least `additional`
138    /// elements to be inserted in the given `Vec<T>`.
139    ///
140    /// Equivalent to [`Vec::try_reserve_exact`].
141    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
142        self.0.try_reserve_exact(additional)
143    }
144
145    /// Shrinks the capacity of the vector as much as possible.
146    ///
147    /// Equivalent to [`Vec::shrink_to_fit`].
148    pub fn shrink_to_fit(&mut self) {
149        self.0.shrink_to_fit();
150    }
151
152    /// Shrinks the capacity of the vector with a lower bound.
153    ///
154    /// Equivalent to [`Vec::shrink_to`].
155    pub fn shrink_to(&mut self, min_capacity: usize) {
156        self.0.shrink_to(min_capacity);
157    }
158
159    /// Converts the vector into `Box<UniqueEntityEquivalentSlice<T>>`.
160    pub fn into_boxed_slice(self) -> Box<UniqueEntityEquivalentSlice<T>> {
161        // SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].
162        unsafe {
163            UniqueEntityEquivalentSlice::from_boxed_slice_unchecked(self.0.into_boxed_slice())
164        }
165    }
166
167    /// Extracts a slice containing the entire vector.
168    pub fn as_slice(&self) -> &UniqueEntityEquivalentSlice<T> {
169        self
170    }
171
172    /// Extracts a mutable slice of the entire vector.
173    pub fn as_mut_slice(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
174        self
175    }
176
177    /// Shortens the vector, keeping the first `len` elements and dropping
178    /// the rest.
179    ///
180    /// Equivalent to [`Vec::truncate`].
181    pub fn truncate(&mut self, len: usize) {
182        self.0.truncate(len);
183    }
184
185    /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
186    /// valid for zero sized reads if the vector didn't allocate.
187    ///
188    /// Equivalent to [`Vec::as_ptr`].
189    pub fn as_ptr(&self) -> *const T {
190        self.0.as_ptr()
191    }
192    /// Returns a raw mutable pointer to the vector's buffer, or a dangling
193    /// raw pointer valid for zero sized reads if the vector didn't allocate.
194    ///
195    /// Equivalent to [`Vec::as_mut_ptr`].
196    pub fn as_mut_ptr(&mut self) -> *mut T {
197        self.0.as_mut_ptr()
198    }
199
200    /// Forces the length of the vector to `new_len`.
201    ///
202    /// Equivalent to [`Vec::set_len`].
203    ///
204    /// # Safety
205    ///
206    /// It must be safe to call [`Vec::set_len`] with these inputs,
207    /// and the resulting [`Vec`] must only contain unique elements.
208    pub unsafe fn set_len(&mut self, new_len: usize) {
209        // SAFETY: Caller ensures it's safe to call `Vec::set_len`
210        unsafe { self.0.set_len(new_len) };
211    }
212
213    /// Removes an element from the vector and returns it.
214    ///
215    /// Equivalent to [`Vec::swap_remove`].
216    pub fn swap_remove(&mut self, index: usize) -> T {
217        self.0.swap_remove(index)
218    }
219
220    /// Inserts an element at position `index` within the vector, shifting all
221    /// elements after it to the right.
222    ///
223    /// Equivalent to [`Vec::insert`].
224    ///
225    /// # Safety
226    ///
227    /// No `T` contained by `self` may equal `element`.
228    pub unsafe fn insert(&mut self, index: usize, element: T) {
229        self.0.insert(index, element);
230    }
231
232    /// Removes and returns the element at position `index` within the vector,
233    /// shifting all elements after it to the left.
234    ///
235    /// Equivalent to [`Vec::remove`].
236    pub fn remove(&mut self, index: usize) -> T {
237        self.0.remove(index)
238    }
239
240    /// Retains only the elements specified by the predicate.
241    ///
242    /// Equivalent to [`Vec::retain`].
243    pub fn retain<F>(&mut self, f: F)
244    where
245        F: FnMut(&T) -> bool,
246    {
247        self.0.retain(f);
248    }
249
250    /// Retains only the elements specified by the predicate, passing a mutable reference to it.
251    ///
252    /// Equivalent to [`Vec::retain_mut`].
253    ///
254    /// # Safety
255    ///
256    /// `self` must only contain unique elements after each individual execution of `f`.
257    pub unsafe fn retain_mut<F>(&mut self, f: F)
258    where
259        F: FnMut(&mut T) -> bool,
260    {
261        self.0.retain_mut(f);
262    }
263
264    /// Removes all but the first of consecutive elements in the vector that resolve to the same
265    /// key.
266    ///
267    /// Equivalent to [`Vec::dedup_by_key`].
268    ///
269    /// # Safety
270    ///
271    /// `self` must only contain unique elements after each individual execution of `key`.
272    pub unsafe fn dedup_by_key<F, K>(&mut self, key: F)
273    where
274        F: FnMut(&mut T) -> K,
275        K: PartialEq,
276    {
277        self.0.dedup_by_key(key);
278    }
279
280    /// Removes all but the first of consecutive elements in the vector satisfying a given equality
281    /// relation.
282    ///
283    /// Equivalent to [`Vec::dedup_by`].
284    ///
285    /// # Safety
286    ///
287    /// `self` must only contain unique elements after each individual execution of `same_bucket`.
288    pub unsafe fn dedup_by<F>(&mut self, same_bucket: F)
289    where
290        F: FnMut(&mut T, &mut T) -> bool,
291    {
292        self.0.dedup_by(same_bucket);
293    }
294
295    /// Appends an element to the back of a collection.
296    ///
297    /// Equivalent to [`Vec::push`].
298    ///
299    /// # Safety
300    ///
301    /// No `T` contained by `self` may equal `element`.
302    pub unsafe fn push(&mut self, value: T) {
303        self.0.push(value);
304    }
305
306    /// Moves all the elements of `other` into `self`, leaving `other` empty.
307    ///
308    /// Equivalent to [`Vec::append`].
309    ///
310    /// # Safety
311    ///
312    /// `other` must contain no elements that equal any element in `self`.
313    pub unsafe fn append(&mut self, other: &mut UniqueEntityEquivalentVec<T>) {
314        self.0.append(&mut other.0);
315    }
316
317    /// Removes the last element from a vector and returns it, or [`None`] if it
318    /// is empty.
319    ///
320    /// Equivalent to [`Vec::pop`].
321    pub fn pop(&mut self) -> Option<T> {
322        self.0.pop()
323    }
324
325    /// Removes the specified range from the vector in bulk, returning all
326    /// removed elements as an iterator.
327    ///
328    /// Equivalent to [`Vec::drain`].
329    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
330    where
331        R: RangeBounds<usize>,
332    {
333        // SAFETY: `self` and thus `range` contains only unique elements.
334        unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.drain(range)) }
335    }
336
337    /// Clears the vector, removing all values.
338    ///
339    /// Equivalent to [`Vec::clear`].
340    pub fn clear(&mut self) {
341        self.0.clear();
342    }
343
344    /// Returns the number of elements in the vector, also referred to
345    /// as its 'length'.
346    ///
347    /// Equivalent to [`Vec::len`].
348    pub fn len(&self) -> usize {
349        self.0.len()
350    }
351
352    /// Returns `true` if the vector contains no elements.
353    ///
354    /// Equivalent to [`Vec::is_empty`].
355    pub fn is_empty(&self) -> bool {
356        self.0.is_empty()
357    }
358
359    /// Splits the collection into two at the given index.
360    ///
361    /// Equivalent to [`Vec::split_off`].
362    pub fn split_off(&mut self, at: usize) -> Self {
363        Self(self.0.split_off(at))
364    }
365
366    /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
367    ///
368    /// Equivalent to [`Vec::resize_with`].
369    ///
370    /// # Safety
371    ///
372    /// `f` must only produce unique `T`, and none of these may equal any `T` in `self`.
373    pub unsafe fn resize_with<F>(&mut self, new_len: usize, f: F)
374    where
375        F: FnMut() -> T,
376    {
377        self.0.resize_with(new_len, f);
378    }
379
380    /// Consumes and leaks the Vec, returning a mutable reference to the contents, `&'a mut UniqueEntityEquivalentSlice<T>`.
381    pub fn leak<'a>(self) -> &'a mut UniqueEntityEquivalentSlice<T> {
382        // SAFETY: All elements in the original slice are unique.
383        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.leak()) }
384    }
385
386    /// Returns the remaining spare capacity of the vector as a slice of
387    /// [`MaybeUninit<T>`].
388    ///
389    /// Equivalent to [`Vec::spare_capacity_mut`].
390    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
391        self.0.spare_capacity_mut()
392    }
393
394    /// Creates a splicing iterator that replaces the specified range in the vector
395    /// with the given `replace_with` iterator and yields the removed items.
396    ///
397    /// Equivalent to [`Vec::splice`].
398    ///
399    /// # Safety
400    ///
401    /// `replace_with` must not yield any elements that equal any elements in `self`,
402    /// except for those in `range`.
403    pub unsafe fn splice<R, I>(
404        &mut self,
405        range: R,
406        replace_with: I,
407    ) -> Splice<'_, <I as IntoIterator>::IntoIter>
408    where
409        R: RangeBounds<usize>,
410        I: EntitySet<Item = T>,
411    {
412        // SAFETY: `self` and thus `range` contains only unique elements.
413        unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.splice(range, replace_with)) }
414    }
415}
416
417impl<T: EntityEquivalent> Default for UniqueEntityEquivalentVec<T> {
418    fn default() -> Self {
419        Self(Vec::default())
420    }
421}
422
423impl<T: EntityEquivalent> Deref for UniqueEntityEquivalentVec<T> {
424    type Target = UniqueEntityEquivalentSlice<T>;
425
426    fn deref(&self) -> &Self::Target {
427        // SAFETY: All elements in the original slice are unique.
428        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(&self.0) }
429    }
430}
431
432impl<T: EntityEquivalent> DerefMut for UniqueEntityEquivalentVec<T> {
433    fn deref_mut(&mut self) -> &mut Self::Target {
434        // SAFETY: All elements in the original slice are unique.
435        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(&mut self.0) }
436    }
437}
438
439impl<'a, T: EntityEquivalent> IntoIterator for &'a UniqueEntityEquivalentVec<T>
440where
441    &'a T: EntityEquivalent,
442{
443    type Item = &'a T;
444
445    type IntoIter = unique_slice::Iter<'a, T>;
446
447    fn into_iter(self) -> Self::IntoIter {
448        // SAFETY: `self` contains only unique elements.
449        unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.iter()) }
450    }
451}
452
453impl<T: EntityEquivalent> IntoIterator for UniqueEntityEquivalentVec<T> {
454    type Item = T;
455
456    type IntoIter = IntoIter<T>;
457
458    fn into_iter(self) -> Self::IntoIter {
459        // SAFETY: `self` contains only unique elements.
460        unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.into_iter()) }
461    }
462}
463
464impl<T: EntityEquivalent> AsMut<Self> for UniqueEntityEquivalentVec<T> {
465    fn as_mut(&mut self) -> &mut UniqueEntityEquivalentVec<T> {
466        self
467    }
468}
469
470impl<T: EntityEquivalent> AsMut<UniqueEntityEquivalentSlice<T>> for UniqueEntityEquivalentVec<T> {
471    fn as_mut(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
472        self
473    }
474}
475
476impl<T: EntityEquivalent> AsRef<Self> for UniqueEntityEquivalentVec<T> {
477    fn as_ref(&self) -> &Self {
478        self
479    }
480}
481
482impl<T: EntityEquivalent> AsRef<Vec<T>> for UniqueEntityEquivalentVec<T> {
483    fn as_ref(&self) -> &Vec<T> {
484        &self.0
485    }
486}
487
488impl<T: EntityEquivalent> Borrow<Vec<T>> for UniqueEntityEquivalentVec<T> {
489    fn borrow(&self) -> &Vec<T> {
490        &self.0
491    }
492}
493
494impl<T: EntityEquivalent> AsRef<[T]> for UniqueEntityEquivalentVec<T> {
495    fn as_ref(&self) -> &[T] {
496        &self.0
497    }
498}
499
500impl<T: EntityEquivalent> AsRef<UniqueEntityEquivalentSlice<T>> for UniqueEntityEquivalentVec<T> {
501    fn as_ref(&self) -> &UniqueEntityEquivalentSlice<T> {
502        self
503    }
504}
505
506impl<T: EntityEquivalent> Borrow<[T]> for UniqueEntityEquivalentVec<T> {
507    fn borrow(&self) -> &[T] {
508        &self.0
509    }
510}
511
512impl<T: EntityEquivalent> Borrow<UniqueEntityEquivalentSlice<T>> for UniqueEntityEquivalentVec<T> {
513    fn borrow(&self) -> &UniqueEntityEquivalentSlice<T> {
514        self
515    }
516}
517
518impl<T: EntityEquivalent> BorrowMut<UniqueEntityEquivalentSlice<T>>
519    for UniqueEntityEquivalentVec<T>
520{
521    fn borrow_mut(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
522        self
523    }
524}
525
526impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<Vec<U>> for UniqueEntityEquivalentVec<T> {
527    fn eq(&self, other: &Vec<U>) -> bool {
528        self.0.eq(other)
529    }
530}
531
532impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<&[U]> for UniqueEntityEquivalentVec<T> {
533    fn eq(&self, other: &&[U]) -> bool {
534        self.0.eq(other)
535    }
536}
537
538impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
539    PartialEq<&UniqueEntityEquivalentSlice<U>> for UniqueEntityEquivalentVec<T>
540{
541    fn eq(&self, other: &&UniqueEntityEquivalentSlice<U>) -> bool {
542        self.0.eq(other)
543    }
544}
545
546impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<&mut [U]> for UniqueEntityEquivalentVec<T> {
547    fn eq(&self, other: &&mut [U]) -> bool {
548        self.0.eq(other)
549    }
550}
551
552impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
553    PartialEq<&mut UniqueEntityEquivalentSlice<U>> for UniqueEntityEquivalentVec<T>
554{
555    fn eq(&self, other: &&mut UniqueEntityEquivalentSlice<U>) -> bool {
556        self.0.eq(other)
557    }
558}
559
560impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<&[U; N]>
561    for UniqueEntityEquivalentVec<T>
562{
563    fn eq(&self, other: &&[U; N]) -> bool {
564        self.0.eq(other)
565    }
566}
567
568impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>
569    PartialEq<&UniqueEntityEquivalentArray<U, N>> for UniqueEntityEquivalentVec<T>
570{
571    fn eq(&self, other: &&UniqueEntityEquivalentArray<U, N>) -> bool {
572        self.0.eq(&other.as_inner())
573    }
574}
575
576impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<&mut [U; N]>
577    for UniqueEntityEquivalentVec<T>
578{
579    fn eq(&self, other: &&mut [U; N]) -> bool {
580        self.0.eq(&**other)
581    }
582}
583
584impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>
585    PartialEq<&mut UniqueEntityEquivalentArray<U, N>> for UniqueEntityEquivalentVec<T>
586{
587    fn eq(&self, other: &&mut UniqueEntityEquivalentArray<U, N>) -> bool {
588        self.0.eq(other.as_inner())
589    }
590}
591
592impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<[U]> for UniqueEntityEquivalentVec<T> {
593    fn eq(&self, other: &[U]) -> bool {
594        self.0.eq(other)
595    }
596}
597
598impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
599    PartialEq<UniqueEntityEquivalentSlice<U>> for UniqueEntityEquivalentVec<T>
600{
601    fn eq(&self, other: &UniqueEntityEquivalentSlice<U>) -> bool {
602        self.0.eq(&**other)
603    }
604}
605
606impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<[U; N]>
607    for UniqueEntityEquivalentVec<T>
608{
609    fn eq(&self, other: &[U; N]) -> bool {
610        self.0.eq(other)
611    }
612}
613
614impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>
615    PartialEq<UniqueEntityEquivalentArray<U, N>> for UniqueEntityEquivalentVec<T>
616{
617    fn eq(&self, other: &UniqueEntityEquivalentArray<U, N>) -> bool {
618        self.0.eq(other.as_inner())
619    }
620}
621
622impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for Vec<T> {
623    fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
624        self.eq(&other.0)
625    }
626}
627
628impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for &[T] {
629    fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
630        self.eq(&other.0)
631    }
632}
633
634impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for &mut [T] {
635    fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
636        self.eq(&other.0)
637    }
638}
639
640impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>
641    PartialEq<UniqueEntityEquivalentVec<U>> for [T]
642{
643    fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
644        self.eq(&other.0)
645    }
646}
647
648impl<T: PartialEq<U> + Clone, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>>
649    for Cow<'_, [T]>
650{
651    fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
652        self.eq(&other.0)
653    }
654}
655
656impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for VecDeque<T> {
657    fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {
658        self.eq(&other.0)
659    }
660}
661
662impl<T: EntityEquivalent + Clone> From<&UniqueEntityEquivalentSlice<T>>
663    for UniqueEntityEquivalentVec<T>
664{
665    fn from(value: &UniqueEntityEquivalentSlice<T>) -> Self {
666        value.to_vec()
667    }
668}
669
670impl<T: EntityEquivalent + Clone> From<&mut UniqueEntityEquivalentSlice<T>>
671    for UniqueEntityEquivalentVec<T>
672{
673    fn from(value: &mut UniqueEntityEquivalentSlice<T>) -> Self {
674        value.to_vec()
675    }
676}
677
678impl<T: EntityEquivalent> From<Box<UniqueEntityEquivalentSlice<T>>>
679    for UniqueEntityEquivalentVec<T>
680{
681    fn from(value: Box<UniqueEntityEquivalentSlice<T>>) -> Self {
682        value.into_vec()
683    }
684}
685
686impl<T: EntityEquivalent> From<Cow<'_, UniqueEntityEquivalentSlice<T>>>
687    for UniqueEntityEquivalentVec<T>
688where
689    UniqueEntityEquivalentSlice<T>: ToOwned<Owned = UniqueEntityEquivalentVec<T>>,
690{
691    fn from(value: Cow<UniqueEntityEquivalentSlice<T>>) -> Self {
692        value.into_owned()
693    }
694}
695
696impl<T: EntityEquivalent + Clone> From<&[T; 1]> for UniqueEntityEquivalentVec<T> {
697    fn from(value: &[T; 1]) -> Self {
698        Self(Vec::from(value))
699    }
700}
701
702impl<T: EntityEquivalent + Clone> From<&[T; 0]> for UniqueEntityEquivalentVec<T> {
703    fn from(value: &[T; 0]) -> Self {
704        Self(Vec::from(value))
705    }
706}
707
708impl<T: EntityEquivalent + Clone> From<&mut [T; 1]> for UniqueEntityEquivalentVec<T> {
709    fn from(value: &mut [T; 1]) -> Self {
710        Self(Vec::from(value))
711    }
712}
713
714impl<T: EntityEquivalent + Clone> From<&mut [T; 0]> for UniqueEntityEquivalentVec<T> {
715    fn from(value: &mut [T; 0]) -> Self {
716        Self(Vec::from(value))
717    }
718}
719
720impl<T: EntityEquivalent> From<[T; 1]> for UniqueEntityEquivalentVec<T> {
721    fn from(value: [T; 1]) -> Self {
722        Self(Vec::from(value))
723    }
724}
725
726impl<T: EntityEquivalent> From<[T; 0]> for UniqueEntityEquivalentVec<T> {
727    fn from(value: [T; 0]) -> Self {
728        Self(Vec::from(value))
729    }
730}
731
732impl<T: EntityEquivalent + Clone, const N: usize> From<&UniqueEntityEquivalentArray<T, N>>
733    for UniqueEntityEquivalentVec<T>
734{
735    fn from(value: &UniqueEntityEquivalentArray<T, N>) -> Self {
736        Self(Vec::from(value.as_inner().clone()))
737    }
738}
739
740impl<T: EntityEquivalent + Clone, const N: usize> From<&mut UniqueEntityEquivalentArray<T, N>>
741    for UniqueEntityEquivalentVec<T>
742{
743    fn from(value: &mut UniqueEntityEquivalentArray<T, N>) -> Self {
744        Self(Vec::from(value.as_inner().clone()))
745    }
746}
747
748impl<T: EntityEquivalent, const N: usize> From<UniqueEntityEquivalentArray<T, N>>
749    for UniqueEntityEquivalentVec<T>
750{
751    fn from(value: UniqueEntityEquivalentArray<T, N>) -> Self {
752        Self(Vec::from(value.into_inner()))
753    }
754}
755
756impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Vec<T> {
757    fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
758        value.0
759    }
760}
761
762impl<'a, T: EntityEquivalent + Clone> From<UniqueEntityEquivalentVec<T>> for Cow<'a, [T]> {
763    fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
764        Cow::from(value.0)
765    }
766}
767
768impl<'a, T: EntityEquivalent + Clone> From<UniqueEntityEquivalentVec<T>>
769    for Cow<'a, UniqueEntityEquivalentSlice<T>>
770{
771    fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
772        Cow::Owned(value)
773    }
774}
775
776impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Arc<[T]> {
777    fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
778        Arc::from(value.0)
779    }
780}
781
782impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>>
783    for Arc<UniqueEntityEquivalentSlice<T>>
784{
785    fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
786        // SAFETY: All elements in the original slice are unique.
787        unsafe { UniqueEntityEquivalentSlice::from_arc_slice_unchecked(Arc::from(value.0)) }
788    }
789}
790
791impl<T: EntityEquivalent + Ord> From<UniqueEntityEquivalentVec<T>> for BinaryHeap<T> {
792    fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
793        BinaryHeap::from(value.0)
794    }
795}
796
797impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Box<[T]> {
798    fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
799        Box::from(value.0)
800    }
801}
802
803impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Rc<[T]> {
804    fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
805        Rc::from(value.0)
806    }
807}
808
809impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>>
810    for Rc<UniqueEntityEquivalentSlice<T>>
811{
812    fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
813        // SAFETY: All elements in the original slice are unique.
814        unsafe { UniqueEntityEquivalentSlice::from_rc_slice_unchecked(Rc::from(value.0)) }
815    }
816}
817
818impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for VecDeque<T> {
819    fn from(value: UniqueEntityEquivalentVec<T>) -> Self {
820        VecDeque::from(value.0)
821    }
822}
823
824impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>> for Box<[T; N]> {
825    type Error = UniqueEntityEquivalentVec<T>;
826
827    fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {
828        Box::try_from(value.0).map_err(UniqueEntityEquivalentVec)
829    }
830}
831
832impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>>
833    for Box<UniqueEntityEquivalentArray<T, N>>
834{
835    type Error = UniqueEntityEquivalentVec<T>;
836
837    fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {
838        Box::try_from(value.0)
839            .map(|v|
840                // SAFETY: All elements in the original Vec are unique.
841                unsafe { UniqueEntityEquivalentArray::from_boxed_array_unchecked(v) })
842            .map_err(UniqueEntityEquivalentVec)
843    }
844}
845
846impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>> for [T; N] {
847    type Error = UniqueEntityEquivalentVec<T>;
848
849    fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {
850        <[T; N] as TryFrom<Vec<T>>>::try_from(value.0).map_err(UniqueEntityEquivalentVec)
851    }
852}
853
854impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>>
855    for UniqueEntityEquivalentArray<T, N>
856{
857    type Error = UniqueEntityEquivalentVec<T>;
858
859    fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {
860        <[T; N] as TryFrom<Vec<T>>>::try_from(value.0)
861            .map(|v|
862            // SAFETY: All elements in the original Vec are unique.
863            unsafe { UniqueEntityEquivalentArray::from_array_unchecked(v) })
864            .map_err(UniqueEntityEquivalentVec)
865    }
866}
867
868impl<T: EntityEquivalent> From<BTreeSet<T>> for UniqueEntityEquivalentVec<T> {
869    fn from(value: BTreeSet<T>) -> Self {
870        Self(value.into_iter().collect::<Vec<T>>())
871    }
872}
873
874impl<T: EntityEquivalent> FromIterator<T> for UniqueEntityEquivalentVec<T> {
875    /// This impl only uses `Eq` to validate uniqueness, resulting in O(n^2) complexity.
876    /// It can make sense for very low N, or if `T` implements neither `Ord` nor `Hash`.
877    /// When possible, use `FromEntitySetIterator::from_entity_iter` instead.
878    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
879        // Matches the `HashSet::from_iter` reservation logic.
880        let iter = iter.into_iter();
881        let unique_vec = Self::with_capacity(iter.size_hint().0);
882        // Internal iteration (fold/for_each) is known to result in better code generation
883        // over a for loop.
884        iter.fold(unique_vec, |mut unique_vec, item| {
885            if !unique_vec.0.contains(&item) {
886                unique_vec.0.push(item);
887            }
888            unique_vec
889        })
890    }
891}
892
893impl<T: EntityEquivalent> FromEntitySetIterator<T> for UniqueEntityEquivalentVec<T> {
894    fn from_entity_set_iter<I: EntitySet<Item = T>>(iter: I) -> Self {
895        // SAFETY: `iter` is an `EntitySet`.
896        unsafe { Self::from_vec_unchecked(Vec::from_iter(iter)) }
897    }
898}
899
900impl<T: EntityEquivalent> Extend<T> for UniqueEntityEquivalentVec<T> {
901    /// Use with caution, because this impl only uses `Eq` to validate uniqueness,
902    /// resulting in O(n^2) complexity.
903    /// It can make sense for very low N, or if `T` implements neither `Ord` nor `Hash`.
904    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
905        // Matches the `HashSet::extend` reservation logic. Their reasoning:
906        //  "Keys may be already present or show multiple times in the iterator.
907        //  Reserve the entire hint lower bound if the map is empty.
908        //  Otherwise reserve half the hint (rounded up), so the map
909        //  will only resize twice in the worst case."
910        let iter = iter.into_iter();
911        let reserve = if self.is_empty() {
912            iter.size_hint().0
913        } else {
914            iter.size_hint().0.div_ceil(2)
915        };
916        self.reserve(reserve);
917        // Internal iteration (fold/for_each) is known to result in better code generation
918        // over a for loop.
919        iter.for_each(move |item| {
920            if !self.0.contains(&item) {
921                self.0.push(item);
922            }
923        });
924    }
925}
926
927impl<'a, T: EntityEquivalent + Copy + 'a> Extend<&'a T> for UniqueEntityEquivalentVec<T> {
928    /// Use with caution, because this impl only uses `Eq` to validate uniqueness,
929    /// resulting in O(n^2) complexity.
930    /// It can make sense for very low N, or if `T` implements neither `Ord` nor `Hash`.
931    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
932        // Matches the `HashSet::extend` reservation logic. Their reasoning:
933        //  "Keys may be already present or show multiple times in the iterator.
934        //  Reserve the entire hint lower bound if the map is empty.
935        //  Otherwise reserve half the hint (rounded up), so the map
936        //  will only resize twice in the worst case."
937        let iter = iter.into_iter();
938        let reserve = if self.is_empty() {
939            iter.size_hint().0
940        } else {
941            iter.size_hint().0.div_ceil(2)
942        };
943        self.reserve(reserve);
944        // Internal iteration (fold/for_each) is known to result in better code generation
945        // over a for loop.
946        iter.for_each(move |item| {
947            if !self.0.contains(item) {
948                self.0.push(*item);
949            }
950        });
951    }
952}
953
954impl<T: EntityEquivalent> Index<(Bound<usize>, Bound<usize>)> for UniqueEntityEquivalentVec<T> {
955    type Output = UniqueEntityEquivalentSlice<T>;
956    fn index(&self, key: (Bound<usize>, Bound<usize>)) -> &Self::Output {
957        // SAFETY: All elements in the original slice are unique.
958        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
959    }
960}
961
962impl<T: EntityEquivalent> Index<Range<usize>> for UniqueEntityEquivalentVec<T> {
963    type Output = UniqueEntityEquivalentSlice<T>;
964    fn index(&self, key: Range<usize>) -> &Self::Output {
965        // SAFETY: All elements in the original slice are unique.
966        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
967    }
968}
969
970impl<T: EntityEquivalent> Index<RangeFrom<usize>> for UniqueEntityEquivalentVec<T> {
971    type Output = UniqueEntityEquivalentSlice<T>;
972    fn index(&self, key: RangeFrom<usize>) -> &Self::Output {
973        // SAFETY: All elements in the original slice are unique.
974        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
975    }
976}
977
978impl<T: EntityEquivalent> Index<RangeFull> for UniqueEntityEquivalentVec<T> {
979    type Output = UniqueEntityEquivalentSlice<T>;
980    fn index(&self, key: RangeFull) -> &Self::Output {
981        // SAFETY: All elements in the original slice are unique.
982        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
983    }
984}
985
986impl<T: EntityEquivalent> Index<RangeInclusive<usize>> for UniqueEntityEquivalentVec<T> {
987    type Output = UniqueEntityEquivalentSlice<T>;
988    fn index(&self, key: RangeInclusive<usize>) -> &Self::Output {
989        // SAFETY: All elements in the original slice are unique.
990        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
991    }
992}
993
994impl<T: EntityEquivalent> Index<RangeTo<usize>> for UniqueEntityEquivalentVec<T> {
995    type Output = UniqueEntityEquivalentSlice<T>;
996    fn index(&self, key: RangeTo<usize>) -> &Self::Output {
997        // SAFETY: All elements in the original slice are unique.
998        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
999    }
1000}
1001
1002impl<T: EntityEquivalent> Index<RangeToInclusive<usize>> for UniqueEntityEquivalentVec<T> {
1003    type Output = UniqueEntityEquivalentSlice<T>;
1004    fn index(&self, key: RangeToInclusive<usize>) -> &Self::Output {
1005        // SAFETY: All elements in the original slice are unique.
1006        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }
1007    }
1008}
1009
1010impl<T: EntityEquivalent> Index<usize> for UniqueEntityEquivalentVec<T> {
1011    type Output = T;
1012    fn index(&self, key: usize) -> &T {
1013        self.0.index(key)
1014    }
1015}
1016
1017impl<T: EntityEquivalent> IndexMut<(Bound<usize>, Bound<usize>)> for UniqueEntityEquivalentVec<T> {
1018    fn index_mut(&mut self, key: (Bound<usize>, Bound<usize>)) -> &mut Self::Output {
1019        // SAFETY: All elements in the original slice are unique.
1020        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
1021    }
1022}
1023
1024impl<T: EntityEquivalent> IndexMut<Range<usize>> for UniqueEntityEquivalentVec<T> {
1025    fn index_mut(&mut self, key: Range<usize>) -> &mut Self::Output {
1026        // SAFETY: All elements in the original slice are unique.
1027        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
1028    }
1029}
1030
1031impl<T: EntityEquivalent> IndexMut<RangeFrom<usize>> for UniqueEntityEquivalentVec<T> {
1032    fn index_mut(&mut self, key: RangeFrom<usize>) -> &mut Self::Output {
1033        // SAFETY: All elements in the original slice are unique.
1034        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
1035    }
1036}
1037
1038impl<T: EntityEquivalent> IndexMut<RangeFull> for UniqueEntityEquivalentVec<T> {
1039    fn index_mut(&mut self, key: RangeFull) -> &mut Self::Output {
1040        // SAFETY: All elements in the original slice are unique.
1041        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
1042    }
1043}
1044
1045impl<T: EntityEquivalent> IndexMut<RangeInclusive<usize>> for UniqueEntityEquivalentVec<T> {
1046    fn index_mut(&mut self, key: RangeInclusive<usize>) -> &mut Self::Output {
1047        // SAFETY: All elements in the original slice are unique.
1048        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
1049    }
1050}
1051
1052impl<T: EntityEquivalent> IndexMut<RangeTo<usize>> for UniqueEntityEquivalentVec<T> {
1053    fn index_mut(&mut self, key: RangeTo<usize>) -> &mut Self::Output {
1054        // SAFETY: All elements in the original slice are unique.
1055        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
1056    }
1057}
1058
1059impl<T: EntityEquivalent> IndexMut<RangeToInclusive<usize>> for UniqueEntityEquivalentVec<T> {
1060    fn index_mut(&mut self, key: RangeToInclusive<usize>) -> &mut Self::Output {
1061        // SAFETY: All elements in the original slice are unique.
1062        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }
1063    }
1064}
1065
1066/// An iterator that moves out of a vector.
1067///
1068/// This `struct` is created by the [`IntoIterator::into_iter`] trait
1069/// method on [`UniqueEntityEquivalentVec`].
1070pub type IntoIter<T = Entity> = UniqueEntityIter<vec::IntoIter<T>>;
1071
1072impl<T: EntityEquivalent> UniqueEntityIter<vec::IntoIter<T>> {
1073    /// Returns the remaining items of this iterator as a slice.
1074    ///
1075    /// Equivalent to [`vec::IntoIter::as_slice`].
1076    pub fn as_slice(&self) -> &UniqueEntityEquivalentSlice<T> {
1077        // SAFETY: All elements in the original slice are unique.
1078        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.as_inner().as_slice()) }
1079    }
1080
1081    /// Returns the remaining items of this iterator as a mutable slice.
1082    ///
1083    /// Equivalent to [`vec::IntoIter::as_mut_slice`].
1084    pub fn as_mut_slice(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {
1085        // SAFETY: All elements in the original slice are unique.
1086        unsafe {
1087            UniqueEntityEquivalentSlice::from_slice_unchecked_mut(
1088                self.as_mut_inner().as_mut_slice(),
1089            )
1090        }
1091    }
1092}
1093
1094/// A draining iterator for [`UniqueEntityEquivalentVec<T>`].
1095///
1096/// This struct is created by [`UniqueEntityEquivalentVec::drain`].
1097/// See its documentation for more.
1098pub type Drain<'a, T = Entity> = UniqueEntityIter<vec::Drain<'a, T>>;
1099
1100impl<'a, T: EntityEquivalent> UniqueEntityIter<vec::Drain<'a, T>> {
1101    /// Returns the remaining items of this iterator as a slice.
1102    ///
1103    /// Equivalent to [`vec::Drain::as_slice`].
1104    pub fn as_slice(&self) -> &UniqueEntityEquivalentSlice<T> {
1105        // SAFETY: All elements in the original slice are unique.
1106        unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.as_inner().as_slice()) }
1107    }
1108}
1109
1110/// A splicing iterator for [`UniqueEntityEquivalentVec`].
1111///
1112/// This struct is created by [`UniqueEntityEquivalentVec::splice`].
1113/// See its documentation for more.
1114pub type Splice<'a, I> = UniqueEntityIter<vec::Splice<'a, I>>;