diff options
author | Schlufi <81391208+Schlufi@users.noreply.github.com> | 2022-01-06 17:57:39 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2022-01-07 12:34:44 +0100 |
commit | 55a77388373b7803600a5ad6fdc3f76d47b08391 (patch) | |
tree | f5a31dc7bc4c4fa5953342d89ba122bdd810ca91 /AK/HashFunctions.h | |
parent | aa6e5e8cdc3dd19529d8e4be5dd33625d27ed270 (diff) | |
download | serenity-55a77388373b7803600a5ad6fdc3f76d47b08391.zip |
AK: Use a full-period xorshift PRNG for double_hash
The previous implementation had some pretty short cycles and two fixed
points (1711463637 and 2389024350). If two keys hashed to one of these
values insertions and lookups would loop forever.
This version is based on a standard xorshift PRNG with period 2**32-1.
The all-zero state is usually forbidden, so we insert it into the cycle
at an arbitrary location.
Diffstat (limited to 'AK/HashFunctions.h')
-rw-r--r-- | AK/HashFunctions.h | 14 |
1 files changed, 9 insertions, 5 deletions
diff --git a/AK/HashFunctions.h b/AK/HashFunctions.h index 951619c4a7..e869b44800 100644 --- a/AK/HashFunctions.h +++ b/AK/HashFunctions.h @@ -21,11 +21,15 @@ constexpr unsigned int_hash(u32 key) constexpr unsigned double_hash(u32 key) { - key = ~key + (key >> 23); - key ^= (key << 12); - key ^= (key >> 7); - key ^= (key << 2); - key ^= (key >> 20); + const unsigned magic = 0xBA5EDB01; + if (key == magic) + return 0u; + if (key == 0u) + key = magic; + + key ^= key << 13; + key ^= key >> 17; + key ^= key << 5; return key; } |