use core::{any::TypeId, hash::Hash}; use bevy_platform::{ collections::HashMap, hash::{Hashed, NoOpHash, PassHash}, }; /// A [`HashMap`] pre-configured to use [`Hashed`] keys and [`PassHash`] passthrough hashing. /// Iteration order only depends on the order of insertions and deletions. pub type PreHashMap = HashMap, V, PassHash>; /// Extension methods intended to add functionality to [`PreHashMap`]. pub trait PreHashMapExt { /// Tries to get or insert the value for the given `key` using the pre-computed hash first. /// If the [`PreHashMap`] does not already contain the `key`, it will clone it and insert /// the value returned by `func`. fn get_or_insert_with V>(&mut self, key: &Hashed, func: F) -> &mut V; } impl PreHashMapExt for PreHashMap { #[inline] fn get_or_insert_with V>(&mut self, key: &Hashed, func: F) -> &mut V { use bevy_platform::collections::hash_map::RawEntryMut; let entry = self .raw_entry_mut() .from_key_hashed_nocheck(key.hash(), key); match entry { RawEntryMut::Occupied(entry) => entry.into_mut(), RawEntryMut::Vacant(entry) => { let (_, value) = entry.insert_hashed_nocheck(key.hash(), key.clone(), func()); value } } } } /// A specialized hashmap type with Key of [`TypeId`] /// Iteration order only depends on the order of insertions and deletions. pub type TypeIdMap = HashMap; #[cfg(test)] mod tests { use super::*; use static_assertions::assert_impl_all; // Check that the HashMaps are Clone if the key/values are Clone assert_impl_all!(PreHashMap::: Clone); #[test] fn fast_typeid_hash() { struct Hasher; impl core::hash::Hasher for Hasher { fn finish(&self) -> u64 { 0 } fn write(&mut self, _: &[u8]) { panic!("Hashing of core::any::TypeId changed"); } fn write_u64(&mut self, _: u64) {} } Hash::hash(&TypeId::of::<()>(), &mut Hasher); } crate::cfg::alloc! { #[test] fn stable_hash_within_same_program_execution() { use alloc::vec::Vec; let mut map_1 = >::default(); let mut map_2 = >::default(); for i in 1..10 { map_1.insert(i, i); map_2.insert(i, i); } assert_eq!( map_1.iter().collect::>(), map_2.iter().collect::>() ); } } }