Path: blob/main/crates/bevy_platform/src/collections/hash_map.rs
6849 views
//! Provides [`HashMap`] based on [hashbrown]'s implementation.1//! Unlike [`hashbrown::HashMap`], [`HashMap`] defaults to [`FixedHasher`]2//! instead of [`RandomState`].3//! This provides determinism by default with an acceptable compromise to denial4//! of service resistance in the context of a game engine.56use core::{7fmt::Debug,8hash::{BuildHasher, Hash},9ops::{Deref, DerefMut, Index},10};1112use hashbrown::{hash_map as hb, Equivalent};1314use crate::hash::FixedHasher;1516#[cfg(feature = "rayon")]17use rayon::prelude::{FromParallelIterator, IntoParallelIterator, ParallelExtend};1819// Re-exports to match `std::collections::hash_map`20pub use {21crate::hash::{DefaultHasher, RandomState},22hb::{23Drain, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, OccupiedEntry, VacantEntry,24Values, ValuesMut,25},26};2728// Additional items from `hashbrown`29pub use hb::{30EntryRef, ExtractIf, OccupiedError, RawEntryBuilder, RawEntryBuilderMut, RawEntryMut,31RawOccupiedEntryMut,32};3334/// Shortcut for [`Entry`](hb::Entry) with [`FixedHasher`] as the default hashing provider.35pub type Entry<'a, K, V, S = FixedHasher> = hb::Entry<'a, K, V, S>;3637/// New-type for [`HashMap`](hb::HashMap) with [`FixedHasher`] as the default hashing provider.38/// Can be trivially converted to and from a [hashbrown] [`HashMap`](hb::HashMap) using [`From`].39///40/// A new-type is used instead of a type alias due to critical methods like [`new`](hb::HashMap::new)41/// being incompatible with Bevy's choice of default hasher.42#[repr(transparent)]43pub struct HashMap<K, V, S = FixedHasher>(hb::HashMap<K, V, S>);4445impl<K, V, S> Clone for HashMap<K, V, S>46where47hb::HashMap<K, V, S>: Clone,48{49#[inline]50fn clone(&self) -> Self {51Self(self.0.clone())52}5354#[inline]55fn clone_from(&mut self, source: &Self) {56self.0.clone_from(&source.0);57}58}5960impl<K, V, S> Debug for HashMap<K, V, S>61where62hb::HashMap<K, V, S>: Debug,63{64#[inline]65fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {66<hb::HashMap<K, V, S> as Debug>::fmt(&self.0, f)67}68}6970impl<K, V, S> Default for HashMap<K, V, S>71where72hb::HashMap<K, V, S>: Default,73{74#[inline]75fn default() -> Self {76Self(Default::default())77}78}7980impl<K, V, S> PartialEq for HashMap<K, V, S>81where82hb::HashMap<K, V, S>: PartialEq,83{84#[inline]85fn eq(&self, other: &Self) -> bool {86self.0.eq(&other.0)87}88}8990impl<K, V, S> Eq for HashMap<K, V, S> where hb::HashMap<K, V, S>: Eq {}9192impl<K, V, S, T> FromIterator<T> for HashMap<K, V, S>93where94hb::HashMap<K, V, S>: FromIterator<T>,95{96#[inline]97fn from_iter<U: IntoIterator<Item = T>>(iter: U) -> Self {98Self(FromIterator::from_iter(iter))99}100}101102impl<K, V, S, T> Index<T> for HashMap<K, V, S>103where104hb::HashMap<K, V, S>: Index<T>,105{106type Output = <hb::HashMap<K, V, S> as Index<T>>::Output;107108#[inline]109fn index(&self, index: T) -> &Self::Output {110self.0.index(index)111}112}113114impl<K, V, S> IntoIterator for HashMap<K, V, S>115where116hb::HashMap<K, V, S>: IntoIterator,117{118type Item = <hb::HashMap<K, V, S> as IntoIterator>::Item;119120type IntoIter = <hb::HashMap<K, V, S> as IntoIterator>::IntoIter;121122#[inline]123fn into_iter(self) -> Self::IntoIter {124self.0.into_iter()125}126}127128impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>129where130&'a hb::HashMap<K, V, S>: IntoIterator,131{132type Item = <&'a hb::HashMap<K, V, S> as IntoIterator>::Item;133134type IntoIter = <&'a hb::HashMap<K, V, S> as IntoIterator>::IntoIter;135136#[inline]137fn into_iter(self) -> Self::IntoIter {138(&self.0).into_iter()139}140}141142impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>143where144&'a mut hb::HashMap<K, V, S>: IntoIterator,145{146type Item = <&'a mut hb::HashMap<K, V, S> as IntoIterator>::Item;147148type IntoIter = <&'a mut hb::HashMap<K, V, S> as IntoIterator>::IntoIter;149150#[inline]151fn into_iter(self) -> Self::IntoIter {152(&mut self.0).into_iter()153}154}155156impl<K, V, S, T> Extend<T> for HashMap<K, V, S>157where158hb::HashMap<K, V, S>: Extend<T>,159{160#[inline]161fn extend<U: IntoIterator<Item = T>>(&mut self, iter: U) {162self.0.extend(iter);163}164}165166impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V, FixedHasher>167where168K: Eq + Hash,169{170fn from(arr: [(K, V); N]) -> Self {171arr.into_iter().collect()172}173}174175impl<K, V, S> From<hb::HashMap<K, V, S>> for HashMap<K, V, S> {176#[inline]177fn from(value: hb::HashMap<K, V, S>) -> Self {178Self(value)179}180}181182impl<K, V, S> From<HashMap<K, V, S>> for hb::HashMap<K, V, S> {183#[inline]184fn from(value: HashMap<K, V, S>) -> Self {185value.0186}187}188189impl<K, V, S> Deref for HashMap<K, V, S> {190type Target = hb::HashMap<K, V, S>;191192#[inline]193fn deref(&self) -> &Self::Target {194&self.0195}196}197198impl<K, V, S> DerefMut for HashMap<K, V, S> {199#[inline]200fn deref_mut(&mut self) -> &mut Self::Target {201&mut self.0202}203}204205#[cfg(feature = "serialize")]206impl<K, V, S> serde::Serialize for HashMap<K, V, S>207where208hb::HashMap<K, V, S>: serde::Serialize,209{210#[inline]211fn serialize<T>(&self, serializer: T) -> Result<T::Ok, T::Error>212where213T: serde::Serializer,214{215self.0.serialize(serializer)216}217}218219#[cfg(feature = "serialize")]220impl<'de, K, V, S> serde::Deserialize<'de> for HashMap<K, V, S>221where222hb::HashMap<K, V, S>: serde::Deserialize<'de>,223{224#[inline]225fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>226where227D: serde::Deserializer<'de>,228{229Ok(Self(serde::Deserialize::deserialize(deserializer)?))230}231}232233#[cfg(feature = "rayon")]234impl<K, V, S, T> FromParallelIterator<T> for HashMap<K, V, S>235where236hb::HashMap<K, V, S>: FromParallelIterator<T>,237T: Send,238{239fn from_par_iter<P>(par_iter: P) -> Self240where241P: IntoParallelIterator<Item = T>,242{243Self(<hb::HashMap<K, V, S> as FromParallelIterator<T>>::from_par_iter(par_iter))244}245}246247#[cfg(feature = "rayon")]248impl<K, V, S> IntoParallelIterator for HashMap<K, V, S>249where250hb::HashMap<K, V, S>: IntoParallelIterator,251{252type Item = <hb::HashMap<K, V, S> as IntoParallelIterator>::Item;253type Iter = <hb::HashMap<K, V, S> as IntoParallelIterator>::Iter;254255fn into_par_iter(self) -> Self::Iter {256self.0.into_par_iter()257}258}259260#[cfg(feature = "rayon")]261impl<'a, K: Sync, V: Sync, S> IntoParallelIterator for &'a HashMap<K, V, S>262where263&'a hb::HashMap<K, V, S>: IntoParallelIterator,264{265type Item = <&'a hb::HashMap<K, V, S> as IntoParallelIterator>::Item;266type Iter = <&'a hb::HashMap<K, V, S> as IntoParallelIterator>::Iter;267268fn into_par_iter(self) -> Self::Iter {269(&self.0).into_par_iter()270}271}272273#[cfg(feature = "rayon")]274impl<'a, K: Sync, V: Sync, S> IntoParallelIterator for &'a mut HashMap<K, V, S>275where276&'a mut hb::HashMap<K, V, S>: IntoParallelIterator,277{278type Item = <&'a mut hb::HashMap<K, V, S> as IntoParallelIterator>::Item;279type Iter = <&'a mut hb::HashMap<K, V, S> as IntoParallelIterator>::Iter;280281fn into_par_iter(self) -> Self::Iter {282(&mut self.0).into_par_iter()283}284}285286#[cfg(feature = "rayon")]287impl<K, V, S, T> ParallelExtend<T> for HashMap<K, V, S>288where289hb::HashMap<K, V, S>: ParallelExtend<T>,290T: Send,291{292fn par_extend<I>(&mut self, par_iter: I)293where294I: IntoParallelIterator<Item = T>,295{296<hb::HashMap<K, V, S> as ParallelExtend<T>>::par_extend(&mut self.0, par_iter);297}298}299300impl<K, V> HashMap<K, V, FixedHasher> {301/// Creates an empty [`HashMap`].302///303/// Refer to [`new`](hb::HashMap::new) for further details.304///305/// # Examples306///307/// ```rust308/// # use bevy_platform::collections::HashMap;309/// #310/// // Creates a HashMap with zero capacity.311/// let map = HashMap::new();312/// #313/// # let mut map = map;314/// # map.insert(0usize, "foo");315/// # assert_eq!(map.get(&0), Some("foo").as_ref());316/// ```317#[inline]318pub const fn new() -> Self {319Self::with_hasher(FixedHasher)320}321322/// Creates an empty [`HashMap`] with the specified capacity.323///324/// Refer to [`with_capacity`](hb::HashMap::with_capacity) for further details.325///326/// # Examples327///328/// ```rust329/// # use bevy_platform::collections::HashMap;330/// #331/// // Creates a HashMap with capacity for at least 5 entries.332/// let map = HashMap::with_capacity(5);333/// #334/// # let mut map = map;335/// # map.insert(0usize, "foo");336/// # assert_eq!(map.get(&0), Some("foo").as_ref());337/// ```338#[inline]339pub fn with_capacity(capacity: usize) -> Self {340Self::with_capacity_and_hasher(capacity, FixedHasher)341}342}343344impl<K, V, S> HashMap<K, V, S> {345/// Creates an empty [`HashMap`] which will use the given hash builder to hash346/// keys.347///348/// Refer to [`with_hasher`](hb::HashMap::with_hasher) for further details.349///350/// # Examples351///352/// ```rust353/// # use bevy_platform::collections::HashMap;354/// # use bevy_platform::hash::FixedHasher as SomeHasher;355/// // Creates a HashMap with the provided hasher.356/// let map = HashMap::with_hasher(SomeHasher);357/// #358/// # let mut map = map;359/// # map.insert(0usize, "foo");360/// # assert_eq!(map.get(&0), Some("foo").as_ref());361/// ```362#[inline]363pub const fn with_hasher(hash_builder: S) -> Self {364Self(hb::HashMap::with_hasher(hash_builder))365}366367/// Creates an empty [`HashMap`] with the specified capacity, using `hash_builder`368/// to hash the keys.369///370/// Refer to [`with_capacity_and_hasher`](hb::HashMap::with_capacity_and_hasher) for further details.371///372/// # Examples373///374/// ```rust375/// # use bevy_platform::collections::HashMap;376/// # use bevy_platform::hash::FixedHasher as SomeHasher;377/// // Creates a HashMap with capacity for 5 entries and the provided hasher.378/// let map = HashMap::with_capacity_and_hasher(5, SomeHasher);379/// #380/// # let mut map = map;381/// # map.insert(0usize, "foo");382/// # assert_eq!(map.get(&0), Some("foo").as_ref());383/// ```384#[inline]385pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {386Self(hb::HashMap::with_capacity_and_hasher(387capacity,388hash_builder,389))390}391392/// Returns a reference to the map's [`BuildHasher`], or `S` parameter.393///394/// Refer to [`hasher`](hb::HashMap::hasher) for further details.395#[inline]396pub fn hasher(&self) -> &S {397self.0.hasher()398}399400/// Returns the number of elements the map can hold without reallocating.401///402/// Refer to [`capacity`](hb::HashMap::capacity) for further details.403///404/// # Examples405///406/// ```rust407/// # use bevy_platform::collections::HashMap;408/// let map = HashMap::with_capacity(5);409///410/// # let map: HashMap<(), ()> = map;411/// #412/// assert!(map.capacity() >= 5);413/// ```414#[inline]415pub fn capacity(&self) -> usize {416self.0.capacity()417}418419/// An iterator visiting all keys in arbitrary order.420/// The iterator element type is `&'a K`.421///422/// Refer to [`keys`](hb::HashMap::keys) for further details.423///424/// # Examples425///426/// ```rust427/// # use bevy_platform::collections::HashMap;428/// #429/// let mut map = HashMap::new();430///431/// map.insert("foo", 0);432/// map.insert("bar", 1);433/// map.insert("baz", 2);434///435/// for key in map.keys() {436/// // foo, bar, baz437/// // Note that the above order is not guaranteed438/// }439/// #440/// # assert_eq!(map.keys().count(), 3);441/// ```442#[inline]443pub fn keys(&self) -> Keys<'_, K, V> {444self.0.keys()445}446447/// An iterator visiting all values in arbitrary order.448/// The iterator element type is `&'a V`.449///450/// Refer to [`values`](hb::HashMap::values) for further details.451///452/// # Examples453///454/// ```rust455/// # use bevy_platform::collections::HashMap;456/// #457/// let mut map = HashMap::new();458///459/// map.insert("foo", 0);460/// map.insert("bar", 1);461/// map.insert("baz", 2);462///463/// for key in map.values() {464/// // 0, 1, 2465/// // Note that the above order is not guaranteed466/// }467/// #468/// # assert_eq!(map.values().count(), 3);469/// ```470#[inline]471pub fn values(&self) -> Values<'_, K, V> {472self.0.values()473}474475/// An iterator visiting all values mutably in arbitrary order.476/// The iterator element type is `&'a mut V`.477///478/// Refer to [`values`](hb::HashMap::values) for further details.479///480/// # Examples481///482/// ```rust483/// # use bevy_platform::collections::HashMap;484/// #485/// let mut map = HashMap::new();486///487/// map.insert("foo", 0);488/// map.insert("bar", 1);489/// map.insert("baz", 2);490///491/// for key in map.values_mut() {492/// // 0, 1, 2493/// // Note that the above order is not guaranteed494/// }495/// #496/// # assert_eq!(map.values_mut().count(), 3);497/// ```498#[inline]499pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {500self.0.values_mut()501}502503/// An iterator visiting all key-value pairs in arbitrary order.504/// The iterator element type is `(&'a K, &'a V)`.505///506/// Refer to [`iter`](hb::HashMap::iter) for further details.507///508/// # Examples509///510/// ```rust511/// # use bevy_platform::collections::HashMap;512/// #513/// let mut map = HashMap::new();514///515/// map.insert("foo", 0);516/// map.insert("bar", 1);517/// map.insert("baz", 2);518///519/// for (key, value) in map.iter() {520/// // ("foo", 0), ("bar", 1), ("baz", 2)521/// // Note that the above order is not guaranteed522/// }523/// #524/// # assert_eq!(map.iter().count(), 3);525/// ```526#[inline]527pub fn iter(&self) -> Iter<'_, K, V> {528self.0.iter()529}530531/// An iterator visiting all key-value pairs in arbitrary order,532/// with mutable references to the values.533/// The iterator element type is `(&'a K, &'a mut V)`.534///535/// Refer to [`iter_mut`](hb::HashMap::iter_mut) for further details.536///537/// # Examples538///539/// ```rust540/// # use bevy_platform::collections::HashMap;541/// #542/// let mut map = HashMap::new();543///544/// map.insert("foo", 0);545/// map.insert("bar", 1);546/// map.insert("baz", 2);547///548/// for (key, value) in map.iter_mut() {549/// // ("foo", 0), ("bar", 1), ("baz", 2)550/// // Note that the above order is not guaranteed551/// }552/// #553/// # assert_eq!(map.iter_mut().count(), 3);554/// ```555#[inline]556pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {557self.0.iter_mut()558}559560/// Returns the number of elements in the map.561///562/// Refer to [`len`](hb::HashMap::len) for further details.563///564/// # Examples565///566/// ```rust567/// # use bevy_platform::collections::HashMap;568/// let mut map = HashMap::new();569///570/// assert_eq!(map.len(), 0);571///572/// map.insert("foo", 0);573///574/// assert_eq!(map.len(), 1);575/// ```576#[inline]577pub fn len(&self) -> usize {578self.0.len()579}580581/// Returns `true` if the map contains no elements.582///583/// Refer to [`is_empty`](hb::HashMap::is_empty) for further details.584///585/// # Examples586///587/// ```rust588/// # use bevy_platform::collections::HashMap;589/// let mut map = HashMap::new();590///591/// assert!(map.is_empty());592///593/// map.insert("foo", 0);594///595/// assert!(!map.is_empty());596/// ```597#[inline]598pub fn is_empty(&self) -> bool {599self.0.is_empty()600}601602/// Clears the map, returning all key-value pairs as an iterator. Keeps the603/// allocated memory for reuse.604///605/// Refer to [`drain`](hb::HashMap::drain) for further details.606///607/// # Examples608///609/// ```rust610/// # use bevy_platform::collections::HashMap;611/// #612/// let mut map = HashMap::new();613///614/// map.insert("foo", 0);615/// map.insert("bar", 1);616/// map.insert("baz", 2);617///618/// for (key, value) in map.drain() {619/// // ("foo", 0), ("bar", 1), ("baz", 2)620/// // Note that the above order is not guaranteed621/// }622///623/// assert!(map.is_empty());624/// ```625#[inline]626pub fn drain(&mut self) -> Drain<'_, K, V> {627self.0.drain()628}629630/// Retains only the elements specified by the predicate. Keeps the631/// allocated memory for reuse.632///633/// Refer to [`retain`](hb::HashMap::retain) for further details.634///635/// # Examples636///637/// ```rust638/// # use bevy_platform::collections::HashMap;639/// #640/// let mut map = HashMap::new();641///642/// map.insert("foo", 0);643/// map.insert("bar", 1);644/// map.insert("baz", 2);645///646/// map.retain(|key, value| *value == 2);647///648/// assert_eq!(map.len(), 1);649/// ```650#[inline]651pub fn retain<F>(&mut self, f: F)652where653F: FnMut(&K, &mut V) -> bool,654{655self.0.retain(f);656}657658/// Drains elements which are true under the given predicate,659/// and returns an iterator over the removed items.660///661/// Refer to [`extract_if`](hb::HashMap::extract_if) for further details.662///663/// # Examples664///665/// ```rust666/// # use bevy_platform::collections::HashMap;667/// #668/// let mut map = HashMap::new();669///670/// map.insert("foo", 0);671/// map.insert("bar", 1);672/// map.insert("baz", 2);673///674/// let extracted = map675/// .extract_if(|key, value| *value == 2)676/// .collect::<Vec<_>>();677///678/// assert_eq!(map.len(), 2);679/// assert_eq!(extracted.len(), 1);680/// ```681#[inline]682pub fn extract_if<F>(&mut self, f: F) -> ExtractIf<'_, K, V, F>683where684F: FnMut(&K, &mut V) -> bool,685{686self.0.extract_if(f)687}688689/// Clears the map, removing all key-value pairs. Keeps the allocated memory690/// for reuse.691///692/// Refer to [`clear`](hb::HashMap::clear) for further details.693///694/// # Examples695///696/// ```rust697/// # use bevy_platform::collections::HashMap;698/// #699/// let mut map = HashMap::new();700///701/// map.insert("foo", 0);702/// map.insert("bar", 1);703/// map.insert("baz", 2);704///705/// map.clear();706///707/// assert!(map.is_empty());708/// ```709#[inline]710pub fn clear(&mut self) {711self.0.clear();712}713714/// Creates a consuming iterator visiting all the keys in arbitrary order.715/// The map cannot be used after calling this.716/// The iterator element type is `K`.717///718/// Refer to [`into_keys`](hb::HashMap::into_keys) for further details.719///720/// # Examples721///722/// ```rust723/// # use bevy_platform::collections::HashMap;724/// #725/// let mut map = HashMap::new();726///727/// map.insert("foo", 0);728/// map.insert("bar", 1);729/// map.insert("baz", 2);730///731/// for key in map.into_keys() {732/// // "foo", "bar", "baz"733/// // Note that the above order is not guaranteed734/// }735/// ```736#[inline]737pub fn into_keys(self) -> IntoKeys<K, V> {738self.0.into_keys()739}740741/// Creates a consuming iterator visiting all the values in arbitrary order.742/// The map cannot be used after calling this.743/// The iterator element type is `V`.744///745/// Refer to [`into_values`](hb::HashMap::into_values) for further details.746///747/// # Examples748///749/// ```rust750/// # use bevy_platform::collections::HashMap;751/// #752/// let mut map = HashMap::new();753///754/// map.insert("foo", 0);755/// map.insert("bar", 1);756/// map.insert("baz", 2);757///758/// for key in map.into_values() {759/// // 0, 1, 2760/// // Note that the above order is not guaranteed761/// }762/// ```763#[inline]764pub fn into_values(self) -> IntoValues<K, V> {765self.0.into_values()766}767768/// Takes the inner [`HashMap`](hb::HashMap) out of this wrapper.769///770/// # Examples771///772/// ```rust773/// # use bevy_platform::collections::HashMap;774/// let map: HashMap<&'static str, usize> = HashMap::new();775/// let map: hashbrown::HashMap<&'static str, usize, _> = map.into_inner();776/// ```777#[inline]778pub fn into_inner(self) -> hb::HashMap<K, V, S> {779self.0780}781}782783impl<K, V, S> HashMap<K, V, S>784where785K: Eq + Hash,786S: BuildHasher,787{788/// Reserves capacity for at least `additional` more elements to be inserted789/// in the [`HashMap`]. The collection may reserve more space to avoid790/// frequent reallocations.791///792/// Refer to [`reserve`](hb::HashMap::reserve) for further details.793///794/// # Examples795///796/// ```rust797/// # use bevy_platform::collections::HashMap;798/// let mut map = HashMap::with_capacity(5);799///800/// # let mut map: HashMap<(), ()> = map;801/// #802/// assert!(map.capacity() >= 5);803///804/// map.reserve(10);805///806/// assert!(map.capacity() - map.len() >= 10);807/// ```808#[inline]809pub fn reserve(&mut self, additional: usize) {810self.0.reserve(additional);811}812813/// Tries to reserve capacity for at least `additional` more elements to be inserted814/// in the given `HashMap<K,V>`. The collection may reserve more space to avoid815/// frequent reallocations.816///817/// Refer to [`try_reserve`](hb::HashMap::try_reserve) for further details.818///819/// # Examples820///821/// ```rust822/// # use bevy_platform::collections::HashMap;823/// let mut map = HashMap::with_capacity(5);824///825/// # let mut map: HashMap<(), ()> = map;826/// #827/// assert!(map.capacity() >= 5);828///829/// map.try_reserve(10).expect("Out of Memory!");830///831/// assert!(map.capacity() - map.len() >= 10);832/// ```833#[inline]834pub fn try_reserve(&mut self, additional: usize) -> Result<(), hashbrown::TryReserveError> {835self.0.try_reserve(additional)836}837838/// Shrinks the capacity of the map as much as possible. It will drop839/// down as much as possible while maintaining the internal rules840/// and possibly leaving some space in accordance with the resize policy.841///842/// Refer to [`shrink_to_fit`](hb::HashMap::shrink_to_fit) for further details.843///844/// # Examples845///846/// ```rust847/// # use bevy_platform::collections::HashMap;848/// let mut map = HashMap::with_capacity(5);849///850/// map.insert("foo", 0);851/// map.insert("bar", 1);852/// map.insert("baz", 2);853///854/// assert!(map.capacity() >= 5);855///856/// map.shrink_to_fit();857///858/// assert_eq!(map.capacity(), 3);859/// ```860#[inline]861pub fn shrink_to_fit(&mut self) {862self.0.shrink_to_fit();863}864865/// Shrinks the capacity of the map with a lower limit. It will drop866/// down no lower than the supplied limit while maintaining the internal rules867/// and possibly leaving some space in accordance with the resize policy.868///869/// Refer to [`shrink_to`](hb::HashMap::shrink_to) for further details.870#[inline]871pub fn shrink_to(&mut self, min_capacity: usize) {872self.0.shrink_to(min_capacity);873}874875/// Gets the given key's corresponding entry in the map for in-place manipulation.876///877/// Refer to [`entry`](hb::HashMap::entry) for further details.878///879/// # Examples880///881/// ```rust882/// # use bevy_platform::collections::HashMap;883/// let mut map = HashMap::new();884///885/// let value = map.entry("foo").or_insert(0);886/// #887/// # assert_eq!(*value, 0);888/// ```889#[inline]890pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S> {891self.0.entry(key)892}893894/// Gets the given key's corresponding entry by reference in the map for in-place manipulation.895///896/// Refer to [`entry_ref`](hb::HashMap::entry_ref) for further details.897///898/// # Examples899///900/// ```rust901/// # use bevy_platform::collections::HashMap;902/// let mut map = HashMap::new();903/// # let mut map: HashMap<&'static str, usize> = map;904///905/// let value = map.entry_ref("foo").or_insert(0);906/// #907/// # assert_eq!(*value, 0);908/// ```909#[inline]910pub fn entry_ref<'a, 'b, Q>(&'a mut self, key: &'b Q) -> EntryRef<'a, 'b, K, Q, V, S>911where912Q: Hash + Equivalent<K> + ?Sized,913{914self.0.entry_ref(key)915}916917/// Returns a reference to the value corresponding to the key.918///919/// Refer to [`get`](hb::HashMap::get) for further details.920///921/// # Examples922///923/// ```rust924/// # use bevy_platform::collections::HashMap;925/// let mut map = HashMap::new();926///927/// map.insert("foo", 0);928///929/// assert_eq!(map.get("foo"), Some(&0));930/// ```931#[inline]932pub fn get<Q>(&self, k: &Q) -> Option<&V>933where934Q: Hash + Equivalent<K> + ?Sized,935{936self.0.get(k)937}938939/// Returns the key-value pair corresponding to the supplied key.940///941/// Refer to [`get_key_value`](hb::HashMap::get_key_value) for further details.942///943/// # Examples944///945/// ```rust946/// # use bevy_platform::collections::HashMap;947/// let mut map = HashMap::new();948///949/// map.insert("foo", 0);950///951/// assert_eq!(map.get_key_value("foo"), Some((&"foo", &0)));952/// ```953#[inline]954pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>955where956Q: Hash + Equivalent<K> + ?Sized,957{958self.0.get_key_value(k)959}960961/// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value.962///963/// Refer to [`get_key_value_mut`](hb::HashMap::get_key_value_mut) for further details.964///965/// # Examples966///967/// ```rust968/// # use bevy_platform::collections::HashMap;969/// let mut map = HashMap::new();970///971/// map.insert("foo", 0);972///973/// assert_eq!(map.get_key_value_mut("foo"), Some((&"foo", &mut 0)));974/// ```975#[inline]976pub fn get_key_value_mut<Q>(&mut self, k: &Q) -> Option<(&K, &mut V)>977where978Q: Hash + Equivalent<K> + ?Sized,979{980self.0.get_key_value_mut(k)981}982983/// Returns `true` if the map contains a value for the specified key.984///985/// Refer to [`contains_key`](hb::HashMap::contains_key) for further details.986///987/// # Examples988///989/// ```rust990/// # use bevy_platform::collections::HashMap;991/// let mut map = HashMap::new();992///993/// map.insert("foo", 0);994///995/// assert!(map.contains_key("foo"));996/// ```997#[inline]998pub fn contains_key<Q>(&self, k: &Q) -> bool999where1000Q: Hash + Equivalent<K> + ?Sized,1001{1002self.0.contains_key(k)1003}10041005/// Returns a mutable reference to the value corresponding to the key.1006///1007/// Refer to [`get_mut`](hb::HashMap::get_mut) for further details.1008///1009/// # Examples1010///1011/// ```rust1012/// # use bevy_platform::collections::HashMap;1013/// let mut map = HashMap::new();1014///1015/// map.insert("foo", 0);1016///1017/// assert_eq!(map.get_mut("foo"), Some(&mut 0));1018/// ```1019#[inline]1020pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>1021where1022Q: Hash + Equivalent<K> + ?Sized,1023{1024self.0.get_mut(k)1025}10261027/// Attempts to get mutable references to `N` values in the map at once.1028///1029/// Refer to [`get_many_mut`](hb::HashMap::get_many_mut) for further details.1030///1031/// # Examples1032///1033/// ```rust1034/// # use bevy_platform::collections::HashMap;1035/// let mut map = HashMap::new();1036///1037/// map.insert("foo", 0);1038/// map.insert("bar", 1);1039/// map.insert("baz", 2);1040///1041/// let result = map.get_many_mut(["foo", "bar"]);1042///1043/// assert_eq!(result, [Some(&mut 0), Some(&mut 1)]);1044/// ```1045#[inline]1046pub fn get_many_mut<Q, const N: usize>(&mut self, ks: [&Q; N]) -> [Option<&'_ mut V>; N]1047where1048Q: Hash + Equivalent<K> + ?Sized,1049{1050self.0.get_many_mut(ks)1051}10521053/// Attempts to get mutable references to `N` values in the map at once, with immutable1054/// references to the corresponding keys.1055///1056/// Refer to [`get_many_key_value_mut`](hb::HashMap::get_many_key_value_mut) for further details.1057///1058/// # Examples1059///1060/// ```rust1061/// # use bevy_platform::collections::HashMap;1062/// let mut map = HashMap::new();1063///1064/// map.insert("foo", 0);1065/// map.insert("bar", 1);1066/// map.insert("baz", 2);1067///1068/// let result = map.get_many_key_value_mut(["foo", "bar"]);1069///1070/// assert_eq!(result, [Some((&"foo", &mut 0)), Some((&"bar", &mut 1))]);1071/// ```1072#[inline]1073pub fn get_many_key_value_mut<Q, const N: usize>(1074&mut self,1075ks: [&Q; N],1076) -> [Option<(&'_ K, &'_ mut V)>; N]1077where1078Q: Hash + Equivalent<K> + ?Sized,1079{1080self.0.get_many_key_value_mut(ks)1081}10821083/// Inserts a key-value pair into the map.1084///1085/// Refer to [`insert`](hb::HashMap::insert) for further details.1086///1087/// # Examples1088///1089/// ```rust1090/// # use bevy_platform::collections::HashMap;1091/// let mut map = HashMap::new();1092///1093/// map.insert("foo", 0);1094///1095/// assert_eq!(map.get("foo"), Some(&0));1096/// ```1097#[inline]1098pub fn insert(&mut self, k: K, v: V) -> Option<V> {1099self.0.insert(k, v)1100}11011102/// Tries to insert a key-value pair into the map, and returns1103/// a mutable reference to the value in the entry.1104///1105/// Refer to [`try_insert`](hb::HashMap::try_insert) for further details.1106///1107/// # Examples1108///1109/// ```rust1110/// # use bevy_platform::collections::HashMap;1111/// let mut map = HashMap::new();1112///1113/// map.try_insert("foo", 0).unwrap();1114///1115/// assert!(map.try_insert("foo", 1).is_err());1116/// ```1117#[inline]1118pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, S>> {1119self.0.try_insert(key, value)1120}11211122/// Removes a key from the map, returning the value at the key if the key1123/// was previously in the map. Keeps the allocated memory for reuse.1124///1125/// Refer to [`remove`](hb::HashMap::remove) for further details.1126///1127/// # Examples1128///1129/// ```rust1130/// # use bevy_platform::collections::HashMap;1131/// let mut map = HashMap::new();1132///1133/// map.insert("foo", 0);1134///1135/// assert_eq!(map.remove("foo"), Some(0));1136///1137/// assert!(map.is_empty());1138/// ```1139#[inline]1140pub fn remove<Q>(&mut self, k: &Q) -> Option<V>1141where1142Q: Hash + Equivalent<K> + ?Sized,1143{1144self.0.remove(k)1145}11461147/// Removes a key from the map, returning the stored key and value if the1148/// key was previously in the map. Keeps the allocated memory for reuse.1149///1150/// Refer to [`remove_entry`](hb::HashMap::remove_entry) for further details.1151///1152/// # Examples1153///1154/// ```rust1155/// # use bevy_platform::collections::HashMap;1156/// let mut map = HashMap::new();1157///1158/// map.insert("foo", 0);1159///1160/// assert_eq!(map.remove_entry("foo"), Some(("foo", 0)));1161///1162/// assert!(map.is_empty());1163/// ```1164#[inline]1165pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>1166where1167Q: Hash + Equivalent<K> + ?Sized,1168{1169self.0.remove_entry(k)1170}11711172/// Returns the total amount of memory allocated internally by the hash1173/// set, in bytes.1174///1175/// Refer to [`allocation_size`](hb::HashMap::allocation_size) for further details.1176///1177/// # Examples1178///1179/// ```rust1180/// # use bevy_platform::collections::HashMap;1181/// let mut map = HashMap::new();1182///1183/// assert_eq!(map.allocation_size(), 0);1184///1185/// map.insert("foo", 0u32);1186///1187/// assert!(map.allocation_size() >= size_of::<&'static str>() + size_of::<u32>());1188/// ```1189#[inline]1190pub fn allocation_size(&self) -> usize {1191self.0.allocation_size()1192}11931194/// Insert a key-value pair into the map without checking1195/// if the key already exists in the map.1196///1197/// Refer to [`insert_unique_unchecked`](hb::HashMap::insert_unique_unchecked) for further details.1198///1199/// # Safety1200///1201/// This operation is safe if a key does not exist in the map.1202///1203/// However, if a key exists in the map already, the behavior is unspecified:1204/// this operation may panic, loop forever, or any following operation with the map1205/// may panic, loop forever or return arbitrary result.1206///1207/// That said, this operation (and following operations) are guaranteed to1208/// not violate memory safety.1209///1210/// However this operation is still unsafe because the resulting `HashMap`1211/// may be passed to unsafe code which does expect the map to behave1212/// correctly, and would cause unsoundness as a result.1213#[expect(1214unsafe_code,1215reason = "re-exporting unsafe method from Hashbrown requires unsafe code"1216)]1217#[inline]1218pub unsafe fn insert_unique_unchecked(&mut self, key: K, value: V) -> (&K, &mut V) {1219// SAFETY: safety contract is ensured by the caller.1220unsafe { self.0.insert_unique_unchecked(key, value) }1221}12221223/// Attempts to get mutable references to `N` values in the map at once, without validating that1224/// the values are unique.1225///1226/// Refer to [`get_many_unchecked_mut`](hb::HashMap::get_many_unchecked_mut) for further details.1227///1228/// Returns an array of length `N` with the results of each query. `None` will be used if1229/// the key is missing.1230///1231/// For a safe alternative see [`get_many_mut`](`HashMap::get_many_mut`).1232///1233/// # Safety1234///1235/// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting1236/// references are not used.1237///1238/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html1239#[expect(1240unsafe_code,1241reason = "re-exporting unsafe method from Hashbrown requires unsafe code"1242)]1243#[inline]1244pub unsafe fn get_many_unchecked_mut<Q, const N: usize>(1245&mut self,1246keys: [&Q; N],1247) -> [Option<&'_ mut V>; N]1248where1249Q: Hash + Equivalent<K> + ?Sized,1250{1251// SAFETY: safety contract is ensured by the caller.1252unsafe { self.0.get_many_unchecked_mut(keys) }1253}12541255/// Attempts to get mutable references to `N` values in the map at once, with immutable1256/// references to the corresponding keys, without validating that the values are unique.1257///1258/// Refer to [`get_many_key_value_unchecked_mut`](hb::HashMap::get_many_key_value_unchecked_mut) for further details.1259///1260/// Returns an array of length `N` with the results of each query. `None` will be returned if1261/// any of the keys are missing.1262///1263/// For a safe alternative see [`get_many_key_value_mut`](`HashMap::get_many_key_value_mut`).1264///1265/// # Safety1266///1267/// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting1268/// references are not used.1269///1270/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html1271#[expect(1272unsafe_code,1273reason = "re-exporting unsafe method from Hashbrown requires unsafe code"1274)]1275#[inline]1276pub unsafe fn get_many_key_value_unchecked_mut<Q, const N: usize>(1277&mut self,1278keys: [&Q; N],1279) -> [Option<(&'_ K, &'_ mut V)>; N]1280where1281Q: Hash + Equivalent<K> + ?Sized,1282{1283// SAFETY: safety contract is ensured by the caller.1284unsafe { self.0.get_many_key_value_unchecked_mut(keys) }1285}1286}128712881289