Skip to content

Commit

Permalink
Make TypeId::hash more robust in case of upstream rustc changes (#1…
Browse files Browse the repository at this point in the history
…1334)

Based on discussion after #11268 was merged:
Instead of panicking should the impl of `TypeId::hash` change
significantly, have a fallback and detect this in a test.
  • Loading branch information
SpecificProtagonist authored Jan 14, 2024
1 parent 03404c4 commit cd12e7c
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions crates/bevy_ecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,13 @@ impl std::hash::Hasher for NoOpTypeIdHasher {
self.0
}

fn write(&mut self, _bytes: &[u8]) {
fn write(&mut self, bytes: &[u8]) {
// This will never be called: TypeId always just calls write_u64 once!
// This is unlikely to ever change, but as it isn't officially guaranteed,
// panicking will let us detect this as fast as possible.
unimplemented!("Hashing of std::any::TypeId changed");
// This is a known trick and unlikely to change, but isn't officially guaranteed.
// Don't break applications (slower fallback, just check in test):
self.0 = bytes.iter().fold(self.0, |hash, b| {
hash.rotate_left(8).wrapping_add(*b as u64)
});
}

fn write_u64(&mut self, i: u64) {
Expand Down Expand Up @@ -1750,6 +1752,23 @@ mod tests {
);
}

#[test]
fn fast_typeid_hash() {
struct Hasher;

impl std::hash::Hasher for Hasher {
fn finish(&self) -> u64 {
0
}
fn write(&mut self, _: &[u8]) {
panic!("Hashing of std::any::TypeId changed");
}
fn write_u64(&mut self, _: u64) {}
}

std::hash::Hash::hash(&TypeId::of::<()>(), &mut Hasher);
}

#[derive(Component)]
struct ComponentA(u32);

Expand Down

0 comments on commit cd12e7c

Please sign in to comment.