Path: blob/main/crates/bevy_ecs/src/entity/unique_vec.rs
6849 views
//! A wrapper around entity [`Vec`]s with a uniqueness invariant.12use core::{3borrow::{Borrow, BorrowMut},4mem::MaybeUninit,5ops::{6Bound, Deref, DerefMut, Index, IndexMut, Range, RangeBounds, RangeFrom, RangeFull,7RangeInclusive, RangeTo, RangeToInclusive,8},9};1011use alloc::{12borrow::{Cow, ToOwned},13boxed::Box,14collections::{BTreeSet, BinaryHeap, TryReserveError, VecDeque},15rc::Rc,16vec::{self, Vec},17};1819use bevy_platform::sync::Arc;2021use super::{22unique_slice::{self, UniqueEntityEquivalentSlice},23Entity, EntityEquivalent, EntitySet, FromEntitySetIterator, UniqueEntityEquivalentArray,24UniqueEntityIter,25};2627/// A `Vec` that contains only unique entities.28///29/// "Unique" means that `x != y` holds for any 2 entities in this collection.30/// This is always true when less than 2 entities are present.31///32/// This type is best obtained by its `FromEntitySetIterator` impl, via either33/// `EntityIterator::collect_set` or `UniqueEntityEquivalentVec::from_entity_iter`.34///35/// While this type can be constructed via `Iterator::collect`, doing so is inefficient,36/// and not recommended.37///38/// When `T` is [`Entity`], use the [`UniqueEntityVec`] alias.39#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]40pub struct UniqueEntityEquivalentVec<T: EntityEquivalent>(Vec<T>);4142/// A `Vec` that contains only unique [`Entity`].43///44/// This is the default case of a [`UniqueEntityEquivalentVec`].45pub type UniqueEntityVec = UniqueEntityEquivalentVec<Entity>;4647impl<T: EntityEquivalent> UniqueEntityEquivalentVec<T> {48/// Constructs a new, empty `UniqueEntityEquivalentVec<T>`.49///50/// Equivalent to [`Vec::new`].51pub const fn new() -> Self {52Self(Vec::new())53}5455/// Constructs a new, empty `UniqueEntityEquivalentVec<T>` with at least the specified capacity.56///57/// Equivalent to [`Vec::with_capacity`]58pub fn with_capacity(capacity: usize) -> Self {59Self(Vec::with_capacity(capacity))60}6162/// Creates a `UniqueEntityEquivalentVec<T>` directly from a pointer, a length, and a capacity.63///64/// Equivalent to [`Vec::from_raw_parts`].65///66/// # Safety67///68/// It must be safe to call [`Vec::from_raw_parts`] with these inputs,69/// and the resulting [`Vec`] must only contain unique elements.70pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {71// SAFETY: Caller ensures it's safe to call `Vec::from_raw_parts`72Self(unsafe { Vec::from_raw_parts(ptr, length, capacity) })73}7475/// Constructs a `UniqueEntityEquivalentVec` from a [`Vec<T>`] unsafely.76///77/// # Safety78///79/// `vec` must contain only unique elements.80pub unsafe fn from_vec_unchecked(vec: Vec<T>) -> Self {81Self(vec)82}8384/// Returns the inner [`Vec<T>`].85pub fn into_inner(self) -> Vec<T> {86self.087}8889/// Returns a reference to the inner [`Vec<T>`].90pub fn as_vec(&self) -> &Vec<T> {91&self.092}9394/// Returns a mutable reference to the inner [`Vec<T>`].95///96/// # Safety97///98/// The elements of this `Vec` must always remain unique, even while99/// this mutable reference is live.100pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<T> {101&mut self.0102}103104/// Returns the total number of elements the vector can hold without105/// reallocating.106///107/// Equivalent to [`Vec::capacity`].108pub fn capacity(&self) -> usize {109self.0.capacity()110}111112/// Reserves capacity for at least `additional` more elements to be inserted113/// in the given `Vec<T>`.114///115/// Equivalent to [`Vec::reserve`].116pub fn reserve(&mut self, additional: usize) {117self.0.reserve(additional);118}119120/// Reserves the minimum capacity for at least `additional` more elements to121/// be inserted in the given `UniqueEntityEquivalentVec<T>`.122///123/// Equivalent to [`Vec::reserve_exact`].124pub fn reserve_exact(&mut self, additional: usize) {125self.0.reserve_exact(additional);126}127128/// Tries to reserve capacity for at least `additional` more elements to be inserted129/// in the given `Vec<T>`.130///131/// Equivalent to [`Vec::try_reserve`].132pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {133self.0.try_reserve(additional)134}135136/// Tries to reserve the minimum capacity for at least `additional`137/// elements to be inserted in the given `Vec<T>`.138///139/// Equivalent to [`Vec::try_reserve_exact`].140pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {141self.0.try_reserve_exact(additional)142}143144/// Shrinks the capacity of the vector as much as possible.145///146/// Equivalent to [`Vec::shrink_to_fit`].147pub fn shrink_to_fit(&mut self) {148self.0.shrink_to_fit();149}150151/// Shrinks the capacity of the vector with a lower bound.152///153/// Equivalent to [`Vec::shrink_to`].154pub fn shrink_to(&mut self, min_capacity: usize) {155self.0.shrink_to(min_capacity);156}157158/// Converts the vector into `Box<UniqueEntityEquivalentSlice<T>>`.159pub fn into_boxed_slice(self) -> Box<UniqueEntityEquivalentSlice<T>> {160// SAFETY: UniqueEntityEquivalentSlice is a transparent wrapper around [T].161unsafe {162UniqueEntityEquivalentSlice::from_boxed_slice_unchecked(self.0.into_boxed_slice())163}164}165166/// Extracts a slice containing the entire vector.167pub fn as_slice(&self) -> &UniqueEntityEquivalentSlice<T> {168self169}170171/// Extracts a mutable slice of the entire vector.172pub fn as_mut_slice(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {173self174}175176/// Shortens the vector, keeping the first `len` elements and dropping177/// the rest.178///179/// Equivalent to [`Vec::truncate`].180pub fn truncate(&mut self, len: usize) {181self.0.truncate(len);182}183184/// Returns a raw pointer to the vector's buffer, or a dangling raw pointer185/// valid for zero sized reads if the vector didn't allocate.186///187/// Equivalent to [`Vec::as_ptr`].188pub fn as_ptr(&self) -> *const T {189self.0.as_ptr()190}191/// Returns a raw mutable pointer to the vector's buffer, or a dangling192/// raw pointer valid for zero sized reads if the vector didn't allocate.193///194/// Equivalent to [`Vec::as_mut_ptr`].195pub fn as_mut_ptr(&mut self) -> *mut T {196self.0.as_mut_ptr()197}198199/// Forces the length of the vector to `new_len`.200///201/// Equivalent to [`Vec::set_len`].202///203/// # Safety204///205/// It must be safe to call [`Vec::set_len`] with these inputs,206/// and the resulting [`Vec`] must only contain unique elements.207pub unsafe fn set_len(&mut self, new_len: usize) {208// SAFETY: Caller ensures it's safe to call `Vec::set_len`209unsafe { self.0.set_len(new_len) };210}211212/// Removes an element from the vector and returns it.213///214/// Equivalent to [`Vec::swap_remove`].215pub fn swap_remove(&mut self, index: usize) -> T {216self.0.swap_remove(index)217}218219/// Inserts an element at position `index` within the vector, shifting all220/// elements after it to the right.221///222/// Equivalent to [`Vec::insert`].223///224/// # Safety225///226/// No `T` contained by `self` may equal `element`.227pub unsafe fn insert(&mut self, index: usize, element: T) {228self.0.insert(index, element);229}230231/// Removes and returns the element at position `index` within the vector,232/// shifting all elements after it to the left.233///234/// Equivalent to [`Vec::remove`].235pub fn remove(&mut self, index: usize) -> T {236self.0.remove(index)237}238239/// Retains only the elements specified by the predicate.240///241/// Equivalent to [`Vec::retain`].242pub fn retain<F>(&mut self, f: F)243where244F: FnMut(&T) -> bool,245{246self.0.retain(f);247}248249/// Retains only the elements specified by the predicate, passing a mutable reference to it.250///251/// Equivalent to [`Vec::retain_mut`].252///253/// # Safety254///255/// `self` must only contain unique elements after each individual execution of `f`.256pub unsafe fn retain_mut<F>(&mut self, f: F)257where258F: FnMut(&mut T) -> bool,259{260self.0.retain_mut(f);261}262263/// Removes all but the first of consecutive elements in the vector that resolve to the same264/// key.265///266/// Equivalent to [`Vec::dedup_by_key`].267///268/// # Safety269///270/// `self` must only contain unique elements after each individual execution of `key`.271pub unsafe fn dedup_by_key<F, K>(&mut self, key: F)272where273F: FnMut(&mut T) -> K,274K: PartialEq,275{276self.0.dedup_by_key(key);277}278279/// Removes all but the first of consecutive elements in the vector satisfying a given equality280/// relation.281///282/// Equivalent to [`Vec::dedup_by`].283///284/// # Safety285///286/// `self` must only contain unique elements after each individual execution of `same_bucket`.287pub unsafe fn dedup_by<F>(&mut self, same_bucket: F)288where289F: FnMut(&mut T, &mut T) -> bool,290{291self.0.dedup_by(same_bucket);292}293294/// Appends an element to the back of a collection.295///296/// Equivalent to [`Vec::push`].297///298/// # Safety299///300/// No `T` contained by `self` may equal `element`.301pub unsafe fn push(&mut self, value: T) {302self.0.push(value);303}304305/// Moves all the elements of `other` into `self`, leaving `other` empty.306///307/// Equivalent to [`Vec::append`].308///309/// # Safety310///311/// `other` must contain no elements that equal any element in `self`.312pub unsafe fn append(&mut self, other: &mut UniqueEntityEquivalentVec<T>) {313self.0.append(&mut other.0);314}315316/// Removes the last element from a vector and returns it, or [`None`] if it317/// is empty.318///319/// Equivalent to [`Vec::pop`].320pub fn pop(&mut self) -> Option<T> {321self.0.pop()322}323324/// Removes the specified range from the vector in bulk, returning all325/// removed elements as an iterator.326///327/// Equivalent to [`Vec::drain`].328pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>329where330R: RangeBounds<usize>,331{332// SAFETY: `self` and thus `range` contains only unique elements.333unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.drain(range)) }334}335336/// Clears the vector, removing all values.337///338/// Equivalent to [`Vec::clear`].339pub fn clear(&mut self) {340self.0.clear();341}342343/// Returns the number of elements in the vector, also referred to344/// as its 'length'.345///346/// Equivalent to [`Vec::len`].347pub fn len(&self) -> usize {348self.0.len()349}350351/// Returns `true` if the vector contains no elements.352///353/// Equivalent to [`Vec::is_empty`].354pub fn is_empty(&self) -> bool {355self.0.is_empty()356}357358/// Splits the collection into two at the given index.359///360/// Equivalent to [`Vec::split_off`].361pub fn split_off(&mut self, at: usize) -> Self {362Self(self.0.split_off(at))363}364365/// Resizes the `Vec` in-place so that `len` is equal to `new_len`.366///367/// Equivalent to [`Vec::resize_with`].368///369/// # Safety370///371/// `f` must only produce unique `T`, and none of these may equal any `T` in `self`.372pub unsafe fn resize_with<F>(&mut self, new_len: usize, f: F)373where374F: FnMut() -> T,375{376self.0.resize_with(new_len, f);377}378379/// Consumes and leaks the Vec, returning a mutable reference to the contents, `&'a mut UniqueEntityEquivalentSlice<T>`.380pub fn leak<'a>(self) -> &'a mut UniqueEntityEquivalentSlice<T> {381// SAFETY: All elements in the original slice are unique.382unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.leak()) }383}384385/// Returns the remaining spare capacity of the vector as a slice of386/// [`MaybeUninit<T>`].387///388/// Equivalent to [`Vec::spare_capacity_mut`].389pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {390self.0.spare_capacity_mut()391}392393/// Creates a splicing iterator that replaces the specified range in the vector394/// with the given `replace_with` iterator and yields the removed items.395///396/// Equivalent to [`Vec::splice`].397///398/// # Safety399///400/// `replace_with` must not yield any elements that equal any elements in `self`,401/// except for those in `range`.402pub unsafe fn splice<R, I>(403&mut self,404range: R,405replace_with: I,406) -> Splice<'_, <I as IntoIterator>::IntoIter>407where408R: RangeBounds<usize>,409I: EntitySet<Item = T>,410{411// SAFETY: `self` and thus `range` contains only unique elements.412unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.splice(range, replace_with)) }413}414}415416impl<T: EntityEquivalent> Default for UniqueEntityEquivalentVec<T> {417fn default() -> Self {418Self(Vec::default())419}420}421422impl<T: EntityEquivalent> Deref for UniqueEntityEquivalentVec<T> {423type Target = UniqueEntityEquivalentSlice<T>;424425fn deref(&self) -> &Self::Target {426// SAFETY: All elements in the original slice are unique.427unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(&self.0) }428}429}430431impl<T: EntityEquivalent> DerefMut for UniqueEntityEquivalentVec<T> {432fn deref_mut(&mut self) -> &mut Self::Target {433// SAFETY: All elements in the original slice are unique.434unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(&mut self.0) }435}436}437438impl<'a, T: EntityEquivalent> IntoIterator for &'a UniqueEntityEquivalentVec<T>439where440&'a T: EntityEquivalent,441{442type Item = &'a T;443444type IntoIter = unique_slice::Iter<'a, T>;445446fn into_iter(self) -> Self::IntoIter {447// SAFETY: `self` contains only unique elements.448unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.iter()) }449}450}451452impl<T: EntityEquivalent> IntoIterator for UniqueEntityEquivalentVec<T> {453type Item = T;454455type IntoIter = IntoIter<T>;456457fn into_iter(self) -> Self::IntoIter {458// SAFETY: `self` contains only unique elements.459unsafe { UniqueEntityIter::from_iterator_unchecked(self.0.into_iter()) }460}461}462463impl<T: EntityEquivalent> AsMut<Self> for UniqueEntityEquivalentVec<T> {464fn as_mut(&mut self) -> &mut UniqueEntityEquivalentVec<T> {465self466}467}468469impl<T: EntityEquivalent> AsMut<UniqueEntityEquivalentSlice<T>> for UniqueEntityEquivalentVec<T> {470fn as_mut(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {471self472}473}474475impl<T: EntityEquivalent> AsRef<Self> for UniqueEntityEquivalentVec<T> {476fn as_ref(&self) -> &Self {477self478}479}480481impl<T: EntityEquivalent> AsRef<Vec<T>> for UniqueEntityEquivalentVec<T> {482fn as_ref(&self) -> &Vec<T> {483&self.0484}485}486487impl<T: EntityEquivalent> Borrow<Vec<T>> for UniqueEntityEquivalentVec<T> {488fn borrow(&self) -> &Vec<T> {489&self.0490}491}492493impl<T: EntityEquivalent> AsRef<[T]> for UniqueEntityEquivalentVec<T> {494fn as_ref(&self) -> &[T] {495&self.0496}497}498499impl<T: EntityEquivalent> AsRef<UniqueEntityEquivalentSlice<T>> for UniqueEntityEquivalentVec<T> {500fn as_ref(&self) -> &UniqueEntityEquivalentSlice<T> {501self502}503}504505impl<T: EntityEquivalent> Borrow<[T]> for UniqueEntityEquivalentVec<T> {506fn borrow(&self) -> &[T] {507&self.0508}509}510511impl<T: EntityEquivalent> Borrow<UniqueEntityEquivalentSlice<T>> for UniqueEntityEquivalentVec<T> {512fn borrow(&self) -> &UniqueEntityEquivalentSlice<T> {513self514}515}516517impl<T: EntityEquivalent> BorrowMut<UniqueEntityEquivalentSlice<T>>518for UniqueEntityEquivalentVec<T>519{520fn borrow_mut(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {521self522}523}524525impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<Vec<U>> for UniqueEntityEquivalentVec<T> {526fn eq(&self, other: &Vec<U>) -> bool {527self.0.eq(other)528}529}530531impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<&[U]> for UniqueEntityEquivalentVec<T> {532fn eq(&self, other: &&[U]) -> bool {533self.0.eq(other)534}535}536537impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>538PartialEq<&UniqueEntityEquivalentSlice<U>> for UniqueEntityEquivalentVec<T>539{540fn eq(&self, other: &&UniqueEntityEquivalentSlice<U>) -> bool {541self.0.eq(other)542}543}544545impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<&mut [U]> for UniqueEntityEquivalentVec<T> {546fn eq(&self, other: &&mut [U]) -> bool {547self.0.eq(other)548}549}550551impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>552PartialEq<&mut UniqueEntityEquivalentSlice<U>> for UniqueEntityEquivalentVec<T>553{554fn eq(&self, other: &&mut UniqueEntityEquivalentSlice<U>) -> bool {555self.0.eq(other)556}557}558559impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<&[U; N]>560for UniqueEntityEquivalentVec<T>561{562fn eq(&self, other: &&[U; N]) -> bool {563self.0.eq(other)564}565}566567impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>568PartialEq<&UniqueEntityEquivalentArray<U, N>> for UniqueEntityEquivalentVec<T>569{570fn eq(&self, other: &&UniqueEntityEquivalentArray<U, N>) -> bool {571self.0.eq(&other.as_inner())572}573}574575impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<&mut [U; N]>576for UniqueEntityEquivalentVec<T>577{578fn eq(&self, other: &&mut [U; N]) -> bool {579self.0.eq(&**other)580}581}582583impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>584PartialEq<&mut UniqueEntityEquivalentArray<U, N>> for UniqueEntityEquivalentVec<T>585{586fn eq(&self, other: &&mut UniqueEntityEquivalentArray<U, N>) -> bool {587self.0.eq(other.as_inner())588}589}590591impl<T: EntityEquivalent + PartialEq<U>, U> PartialEq<[U]> for UniqueEntityEquivalentVec<T> {592fn eq(&self, other: &[U]) -> bool {593self.0.eq(other)594}595}596597impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>598PartialEq<UniqueEntityEquivalentSlice<U>> for UniqueEntityEquivalentVec<T>599{600fn eq(&self, other: &UniqueEntityEquivalentSlice<U>) -> bool {601self.0.eq(&**other)602}603}604605impl<T: EntityEquivalent + PartialEq<U>, U, const N: usize> PartialEq<[U; N]>606for UniqueEntityEquivalentVec<T>607{608fn eq(&self, other: &[U; N]) -> bool {609self.0.eq(other)610}611}612613impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent, const N: usize>614PartialEq<UniqueEntityEquivalentArray<U, N>> for UniqueEntityEquivalentVec<T>615{616fn eq(&self, other: &UniqueEntityEquivalentArray<U, N>) -> bool {617self.0.eq(other.as_inner())618}619}620621impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for Vec<T> {622fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {623self.eq(&other.0)624}625}626627impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for &[T] {628fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {629self.eq(&other.0)630}631}632633impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for &mut [T] {634fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {635self.eq(&other.0)636}637}638639impl<T: EntityEquivalent + PartialEq<U>, U: EntityEquivalent>640PartialEq<UniqueEntityEquivalentVec<U>> for [T]641{642fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {643self.eq(&other.0)644}645}646647impl<T: PartialEq<U> + Clone, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>>648for Cow<'_, [T]>649{650fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {651self.eq(&other.0)652}653}654655impl<T: PartialEq<U>, U: EntityEquivalent> PartialEq<UniqueEntityEquivalentVec<U>> for VecDeque<T> {656fn eq(&self, other: &UniqueEntityEquivalentVec<U>) -> bool {657self.eq(&other.0)658}659}660661impl<T: EntityEquivalent + Clone> From<&UniqueEntityEquivalentSlice<T>>662for UniqueEntityEquivalentVec<T>663{664fn from(value: &UniqueEntityEquivalentSlice<T>) -> Self {665value.to_vec()666}667}668669impl<T: EntityEquivalent + Clone> From<&mut UniqueEntityEquivalentSlice<T>>670for UniqueEntityEquivalentVec<T>671{672fn from(value: &mut UniqueEntityEquivalentSlice<T>) -> Self {673value.to_vec()674}675}676677impl<T: EntityEquivalent> From<Box<UniqueEntityEquivalentSlice<T>>>678for UniqueEntityEquivalentVec<T>679{680fn from(value: Box<UniqueEntityEquivalentSlice<T>>) -> Self {681value.into_vec()682}683}684685impl<T: EntityEquivalent> From<Cow<'_, UniqueEntityEquivalentSlice<T>>>686for UniqueEntityEquivalentVec<T>687where688UniqueEntityEquivalentSlice<T>: ToOwned<Owned = UniqueEntityEquivalentVec<T>>,689{690fn from(value: Cow<UniqueEntityEquivalentSlice<T>>) -> Self {691value.into_owned()692}693}694695impl<T: EntityEquivalent + Clone> From<&[T; 1]> for UniqueEntityEquivalentVec<T> {696fn from(value: &[T; 1]) -> Self {697Self(Vec::from(value))698}699}700701impl<T: EntityEquivalent + Clone> From<&[T; 0]> for UniqueEntityEquivalentVec<T> {702fn from(value: &[T; 0]) -> Self {703Self(Vec::from(value))704}705}706707impl<T: EntityEquivalent + Clone> From<&mut [T; 1]> for UniqueEntityEquivalentVec<T> {708fn from(value: &mut [T; 1]) -> Self {709Self(Vec::from(value))710}711}712713impl<T: EntityEquivalent + Clone> From<&mut [T; 0]> for UniqueEntityEquivalentVec<T> {714fn from(value: &mut [T; 0]) -> Self {715Self(Vec::from(value))716}717}718719impl<T: EntityEquivalent> From<[T; 1]> for UniqueEntityEquivalentVec<T> {720fn from(value: [T; 1]) -> Self {721Self(Vec::from(value))722}723}724725impl<T: EntityEquivalent> From<[T; 0]> for UniqueEntityEquivalentVec<T> {726fn from(value: [T; 0]) -> Self {727Self(Vec::from(value))728}729}730731impl<T: EntityEquivalent + Clone, const N: usize> From<&UniqueEntityEquivalentArray<T, N>>732for UniqueEntityEquivalentVec<T>733{734fn from(value: &UniqueEntityEquivalentArray<T, N>) -> Self {735Self(Vec::from(value.as_inner().clone()))736}737}738739impl<T: EntityEquivalent + Clone, const N: usize> From<&mut UniqueEntityEquivalentArray<T, N>>740for UniqueEntityEquivalentVec<T>741{742fn from(value: &mut UniqueEntityEquivalentArray<T, N>) -> Self {743Self(Vec::from(value.as_inner().clone()))744}745}746747impl<T: EntityEquivalent, const N: usize> From<UniqueEntityEquivalentArray<T, N>>748for UniqueEntityEquivalentVec<T>749{750fn from(value: UniqueEntityEquivalentArray<T, N>) -> Self {751Self(Vec::from(value.into_inner()))752}753}754755impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Vec<T> {756fn from(value: UniqueEntityEquivalentVec<T>) -> Self {757value.0758}759}760761impl<'a, T: EntityEquivalent + Clone> From<UniqueEntityEquivalentVec<T>> for Cow<'a, [T]> {762fn from(value: UniqueEntityEquivalentVec<T>) -> Self {763Cow::from(value.0)764}765}766767impl<'a, T: EntityEquivalent + Clone> From<UniqueEntityEquivalentVec<T>>768for Cow<'a, UniqueEntityEquivalentSlice<T>>769{770fn from(value: UniqueEntityEquivalentVec<T>) -> Self {771Cow::Owned(value)772}773}774775impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Arc<[T]> {776fn from(value: UniqueEntityEquivalentVec<T>) -> Self {777Arc::from(value.0)778}779}780781impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>>782for Arc<UniqueEntityEquivalentSlice<T>>783{784fn from(value: UniqueEntityEquivalentVec<T>) -> Self {785// SAFETY: All elements in the original slice are unique.786unsafe { UniqueEntityEquivalentSlice::from_arc_slice_unchecked(Arc::from(value.0)) }787}788}789790impl<T: EntityEquivalent + Ord> From<UniqueEntityEquivalentVec<T>> for BinaryHeap<T> {791fn from(value: UniqueEntityEquivalentVec<T>) -> Self {792BinaryHeap::from(value.0)793}794}795796impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Box<[T]> {797fn from(value: UniqueEntityEquivalentVec<T>) -> Self {798Box::from(value.0)799}800}801802impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for Rc<[T]> {803fn from(value: UniqueEntityEquivalentVec<T>) -> Self {804Rc::from(value.0)805}806}807808impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>>809for Rc<UniqueEntityEquivalentSlice<T>>810{811fn from(value: UniqueEntityEquivalentVec<T>) -> Self {812// SAFETY: All elements in the original slice are unique.813unsafe { UniqueEntityEquivalentSlice::from_rc_slice_unchecked(Rc::from(value.0)) }814}815}816817impl<T: EntityEquivalent> From<UniqueEntityEquivalentVec<T>> for VecDeque<T> {818fn from(value: UniqueEntityEquivalentVec<T>) -> Self {819VecDeque::from(value.0)820}821}822823impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>> for Box<[T; N]> {824type Error = UniqueEntityEquivalentVec<T>;825826fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {827Box::try_from(value.0).map_err(UniqueEntityEquivalentVec)828}829}830831impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>>832for Box<UniqueEntityEquivalentArray<T, N>>833{834type Error = UniqueEntityEquivalentVec<T>;835836fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {837Box::try_from(value.0)838.map(|v|839// SAFETY: All elements in the original Vec are unique.840unsafe { UniqueEntityEquivalentArray::from_boxed_array_unchecked(v) })841.map_err(UniqueEntityEquivalentVec)842}843}844845impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>> for [T; N] {846type Error = UniqueEntityEquivalentVec<T>;847848fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {849<[T; N] as TryFrom<Vec<T>>>::try_from(value.0).map_err(UniqueEntityEquivalentVec)850}851}852853impl<T: EntityEquivalent, const N: usize> TryFrom<UniqueEntityEquivalentVec<T>>854for UniqueEntityEquivalentArray<T, N>855{856type Error = UniqueEntityEquivalentVec<T>;857858fn try_from(value: UniqueEntityEquivalentVec<T>) -> Result<Self, Self::Error> {859<[T; N] as TryFrom<Vec<T>>>::try_from(value.0)860.map(|v|861// SAFETY: All elements in the original Vec are unique.862unsafe { UniqueEntityEquivalentArray::from_array_unchecked(v) })863.map_err(UniqueEntityEquivalentVec)864}865}866867impl<T: EntityEquivalent> From<BTreeSet<T>> for UniqueEntityEquivalentVec<T> {868fn from(value: BTreeSet<T>) -> Self {869Self(value.into_iter().collect::<Vec<T>>())870}871}872873impl<T: EntityEquivalent> FromIterator<T> for UniqueEntityEquivalentVec<T> {874/// This impl only uses `Eq` to validate uniqueness, resulting in O(n^2) complexity.875/// It can make sense for very low N, or if `T` implements neither `Ord` nor `Hash`.876/// When possible, use `FromEntitySetIterator::from_entity_iter` instead.877fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {878// Matches the `HashSet::from_iter` reservation logic.879let iter = iter.into_iter();880let unique_vec = Self::with_capacity(iter.size_hint().0);881// Internal iteration (fold/for_each) is known to result in better code generation882// over a for loop.883iter.fold(unique_vec, |mut unique_vec, item| {884if !unique_vec.0.contains(&item) {885unique_vec.0.push(item);886}887unique_vec888})889}890}891892impl<T: EntityEquivalent> FromEntitySetIterator<T> for UniqueEntityEquivalentVec<T> {893fn from_entity_set_iter<I: EntitySet<Item = T>>(iter: I) -> Self {894// SAFETY: `iter` is an `EntitySet`.895unsafe { Self::from_vec_unchecked(Vec::from_iter(iter)) }896}897}898899impl<T: EntityEquivalent> Extend<T> for UniqueEntityEquivalentVec<T> {900/// Use with caution, because this impl only uses `Eq` to validate uniqueness,901/// resulting in O(n^2) complexity.902/// It can make sense for very low N, or if `T` implements neither `Ord` nor `Hash`.903fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {904// Matches the `HashSet::extend` reservation logic. Their reasoning:905// "Keys may be already present or show multiple times in the iterator.906// Reserve the entire hint lower bound if the map is empty.907// Otherwise reserve half the hint (rounded up), so the map908// will only resize twice in the worst case."909let iter = iter.into_iter();910let reserve = if self.is_empty() {911iter.size_hint().0912} else {913iter.size_hint().0.div_ceil(2)914};915self.reserve(reserve);916// Internal iteration (fold/for_each) is known to result in better code generation917// over a for loop.918iter.for_each(move |item| {919if !self.0.contains(&item) {920self.0.push(item);921}922});923}924}925926impl<'a, T: EntityEquivalent + Copy + 'a> Extend<&'a T> for UniqueEntityEquivalentVec<T> {927/// Use with caution, because this impl only uses `Eq` to validate uniqueness,928/// resulting in O(n^2) complexity.929/// It can make sense for very low N, or if `T` implements neither `Ord` nor `Hash`.930fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {931// Matches the `HashSet::extend` reservation logic. Their reasoning:932// "Keys may be already present or show multiple times in the iterator.933// Reserve the entire hint lower bound if the map is empty.934// Otherwise reserve half the hint (rounded up), so the map935// will only resize twice in the worst case."936let iter = iter.into_iter();937let reserve = if self.is_empty() {938iter.size_hint().0939} else {940iter.size_hint().0.div_ceil(2)941};942self.reserve(reserve);943// Internal iteration (fold/for_each) is known to result in better code generation944// over a for loop.945iter.for_each(move |item| {946if !self.0.contains(item) {947self.0.push(*item);948}949});950}951}952953impl<T: EntityEquivalent> Index<(Bound<usize>, Bound<usize>)> for UniqueEntityEquivalentVec<T> {954type Output = UniqueEntityEquivalentSlice<T>;955fn index(&self, key: (Bound<usize>, Bound<usize>)) -> &Self::Output {956// SAFETY: All elements in the original slice are unique.957unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }958}959}960961impl<T: EntityEquivalent> Index<Range<usize>> for UniqueEntityEquivalentVec<T> {962type Output = UniqueEntityEquivalentSlice<T>;963fn index(&self, key: Range<usize>) -> &Self::Output {964// SAFETY: All elements in the original slice are unique.965unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }966}967}968969impl<T: EntityEquivalent> Index<RangeFrom<usize>> for UniqueEntityEquivalentVec<T> {970type Output = UniqueEntityEquivalentSlice<T>;971fn index(&self, key: RangeFrom<usize>) -> &Self::Output {972// SAFETY: All elements in the original slice are unique.973unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }974}975}976977impl<T: EntityEquivalent> Index<RangeFull> for UniqueEntityEquivalentVec<T> {978type Output = UniqueEntityEquivalentSlice<T>;979fn index(&self, key: RangeFull) -> &Self::Output {980// SAFETY: All elements in the original slice are unique.981unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }982}983}984985impl<T: EntityEquivalent> Index<RangeInclusive<usize>> for UniqueEntityEquivalentVec<T> {986type Output = UniqueEntityEquivalentSlice<T>;987fn index(&self, key: RangeInclusive<usize>) -> &Self::Output {988// SAFETY: All elements in the original slice are unique.989unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }990}991}992993impl<T: EntityEquivalent> Index<RangeTo<usize>> for UniqueEntityEquivalentVec<T> {994type Output = UniqueEntityEquivalentSlice<T>;995fn index(&self, key: RangeTo<usize>) -> &Self::Output {996// SAFETY: All elements in the original slice are unique.997unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }998}999}10001001impl<T: EntityEquivalent> Index<RangeToInclusive<usize>> for UniqueEntityEquivalentVec<T> {1002type Output = UniqueEntityEquivalentSlice<T>;1003fn index(&self, key: RangeToInclusive<usize>) -> &Self::Output {1004// SAFETY: All elements in the original slice are unique.1005unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.0.index(key)) }1006}1007}10081009impl<T: EntityEquivalent> Index<usize> for UniqueEntityEquivalentVec<T> {1010type Output = T;1011fn index(&self, key: usize) -> &T {1012self.0.index(key)1013}1014}10151016impl<T: EntityEquivalent> IndexMut<(Bound<usize>, Bound<usize>)> for UniqueEntityEquivalentVec<T> {1017fn index_mut(&mut self, key: (Bound<usize>, Bound<usize>)) -> &mut Self::Output {1018// SAFETY: All elements in the original slice are unique.1019unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }1020}1021}10221023impl<T: EntityEquivalent> IndexMut<Range<usize>> for UniqueEntityEquivalentVec<T> {1024fn index_mut(&mut self, key: Range<usize>) -> &mut Self::Output {1025// SAFETY: All elements in the original slice are unique.1026unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }1027}1028}10291030impl<T: EntityEquivalent> IndexMut<RangeFrom<usize>> for UniqueEntityEquivalentVec<T> {1031fn index_mut(&mut self, key: RangeFrom<usize>) -> &mut Self::Output {1032// SAFETY: All elements in the original slice are unique.1033unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }1034}1035}10361037impl<T: EntityEquivalent> IndexMut<RangeFull> for UniqueEntityEquivalentVec<T> {1038fn index_mut(&mut self, key: RangeFull) -> &mut Self::Output {1039// SAFETY: All elements in the original slice are unique.1040unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }1041}1042}10431044impl<T: EntityEquivalent> IndexMut<RangeInclusive<usize>> for UniqueEntityEquivalentVec<T> {1045fn index_mut(&mut self, key: RangeInclusive<usize>) -> &mut Self::Output {1046// SAFETY: All elements in the original slice are unique.1047unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }1048}1049}10501051impl<T: EntityEquivalent> IndexMut<RangeTo<usize>> for UniqueEntityEquivalentVec<T> {1052fn index_mut(&mut self, key: RangeTo<usize>) -> &mut Self::Output {1053// SAFETY: All elements in the original slice are unique.1054unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }1055}1056}10571058impl<T: EntityEquivalent> IndexMut<RangeToInclusive<usize>> for UniqueEntityEquivalentVec<T> {1059fn index_mut(&mut self, key: RangeToInclusive<usize>) -> &mut Self::Output {1060// SAFETY: All elements in the original slice are unique.1061unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked_mut(self.0.index_mut(key)) }1062}1063}10641065/// An iterator that moves out of a vector.1066///1067/// This `struct` is created by the [`IntoIterator::into_iter`] trait1068/// method on [`UniqueEntityEquivalentVec`].1069pub type IntoIter<T = Entity> = UniqueEntityIter<vec::IntoIter<T>>;10701071impl<T: EntityEquivalent> UniqueEntityIter<vec::IntoIter<T>> {1072/// Returns the remaining items of this iterator as a slice.1073///1074/// Equivalent to [`vec::IntoIter::as_slice`].1075pub fn as_slice(&self) -> &UniqueEntityEquivalentSlice<T> {1076// SAFETY: All elements in the original slice are unique.1077unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.as_inner().as_slice()) }1078}10791080/// Returns the remaining items of this iterator as a mutable slice.1081///1082/// Equivalent to [`vec::IntoIter::as_mut_slice`].1083pub fn as_mut_slice(&mut self) -> &mut UniqueEntityEquivalentSlice<T> {1084// SAFETY: All elements in the original slice are unique.1085unsafe {1086UniqueEntityEquivalentSlice::from_slice_unchecked_mut(1087self.as_mut_inner().as_mut_slice(),1088)1089}1090}1091}10921093/// A draining iterator for [`UniqueEntityEquivalentVec<T>`].1094///1095/// This struct is created by [`UniqueEntityEquivalentVec::drain`].1096/// See its documentation for more.1097pub type Drain<'a, T = Entity> = UniqueEntityIter<vec::Drain<'a, T>>;10981099impl<'a, T: EntityEquivalent> UniqueEntityIter<vec::Drain<'a, T>> {1100/// Returns the remaining items of this iterator as a slice.1101///1102/// Equivalent to [`vec::Drain::as_slice`].1103pub fn as_slice(&self) -> &UniqueEntityEquivalentSlice<T> {1104// SAFETY: All elements in the original slice are unique.1105unsafe { UniqueEntityEquivalentSlice::from_slice_unchecked(self.as_inner().as_slice()) }1106}1107}11081109/// A splicing iterator for [`UniqueEntityEquivalentVec`].1110///1111/// This struct is created by [`UniqueEntityEquivalentVec::splice`].1112/// See its documentation for more.1113pub type Splice<'a, I> = UniqueEntityIter<vec::Splice<'a, I>>;111411151116