Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions crates/bevy_ecs/src/entity/hash.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
use core::hash::{BuildHasher, Hasher};
use core::hash::{BuildHasher, Hash, Hasher};

#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};

use crate::{
bundle::Bundle,
world::{
EntityMut, EntityMutExcept, EntityRef, EntityRefExcept, FilteredEntityMut,
FilteredEntityRef,
},
};

use super::Entity;

/// A combination of [`BuildHasher`] and [`Hash`] that can be trusted to behave correctly.
///
/// # Safety
/// When used together, the `Hasher` produced by `Self` and
/// the `Hash` impl of `H` must produce deterministic hashes.
pub unsafe trait TrustedBuildHasher<H: Hash>: BuildHasher {}

/// A [`BuildHasher`] that results in a [`EntityHasher`].
#[derive(Debug, Default, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Default, Clone))]
Expand All @@ -16,8 +33,29 @@ impl BuildHasher for EntityHash {
}
}

// SAFETY: EntityHasher hashes `Entity` deterministically.
unsafe impl TrustedBuildHasher<Entity> for EntityHash {}

// SAFETY: EntityHasher hashes `Entity` deterministically.
unsafe impl TrustedBuildHasher<EntityRef<'_>> for EntityHash {}

// SAFETY: EntityHasher hashes `Entity` deterministically.
unsafe impl TrustedBuildHasher<EntityMut<'_>> for EntityHash {}

// SAFETY: EntityHasher hashes `Entity` deterministically.
unsafe impl TrustedBuildHasher<FilteredEntityRef<'_>> for EntityHash {}

// SAFETY: EntityHasher hashes `Entity` deterministically.
unsafe impl TrustedBuildHasher<FilteredEntityMut<'_>> for EntityHash {}

// SAFETY: EntityHasher hashes `Entity` deterministically.
unsafe impl<B: Bundle> TrustedBuildHasher<EntityRefExcept<'_, B>> for EntityHash {}

// SAFETY: EntityHasher hashes `Entity` deterministically.
unsafe impl<B: Bundle> TrustedBuildHasher<EntityMutExcept<'_, B>> for EntityHash {}

/// A very fast hash that is only designed to work on generational indices
/// like [`Entity`](super::Entity). It will panic if attempting to hash a type containing
/// like [`Entity`]. It will panic if attempting to hash a type containing
/// non-u64 fields.
///
/// This is heavily optimized for typical cases, where you have mostly live
Expand Down
Loading