More principled seeding approach in the hash functions.

This commit is contained in:
Nathan Vegdahl 2022-07-21 12:15:36 -07:00
parent 7082f2d7f4
commit f5a0210cdf

View File

@ -1,35 +1,35 @@
/// A fast seedable 32-bit hash function. /// A fast seedable 32-bit hash function.
///
/// Based on <https://github.com/skeeto/hash-prospector>.
pub fn hash_u32(mut n: u32, seed: u32) -> u32 { pub fn hash_u32(mut n: u32, seed: u32) -> u32 {
n ^= 0xe6fe3beb; // So zero doesn't map to zero. n ^= 0xe6fe3beb; // So zero doesn't map to zero.
n ^= seed; n ^= seed;
// From https://github.com/skeeto/hash-prospector
n ^= n >> 16; n ^= n >> 16;
n = n.wrapping_mul(0x21f0aaad); n = n.wrapping_mul(0x21f0aaad);
n ^= seed;
n ^= n >> 15; n ^= n >> 15;
n = n.wrapping_mul(0xd35a2d97); n = n.wrapping_mul(0xd35a2d97);
n ^= n >> 15; n ^= n >> 15;
n // We xor by `seed` again in case the first time cancelled out our
// "zero doesn't map to zero" precaution.
n ^ seed
} }
/// A fast seedable 64-bit hash function. /// A fast seedable 64-bit hash function.
///
/// Based on <https://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html>.
pub fn hash_u64(mut n: u64, seed: u64) -> u64 { pub fn hash_u64(mut n: u64, seed: u64) -> u64 {
n ^= 0x4acc3f27cc712c9d; // So zero doesn't map to zero. n ^= 0x4acc3f27cc712c9d; // So zero doesn't map to zero.
n ^= seed; n ^= seed;
// From https://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
n ^= n >> 30; n ^= n >> 30;
n = n.wrapping_mul(0xbf58476d1ce4e5b9); n = n.wrapping_mul(0xbf58476d1ce4e5b9);
n ^= seed;
n ^= n >> 27; n ^= n >> 27;
n = n.wrapping_mul(0x94d049bb133111eb); n = n.wrapping_mul(0x94d049bb133111eb);
n ^= n >> 31; n ^= n >> 31;
n // We xor by `seed` again in case the first time cancelled out our
// "zero doesn't map to zero" precaution.
n ^ seed
} }
/// Returns a random float in [0, 1] based on 'n' and a seed. /// Returns a random float in [0, 1] based on 'n' and a seed.