From dd941837e92c3c531f2f887cd79c569f770de797 Mon Sep 17 00:00:00 2001 From: David Gonzalez Martin Date: Sat, 10 Aug 2024 21:06:51 +0200 Subject: [PATCH] Better hash conversion --- bootstrap/lib.h | 8 ++++++++ bootstrap/main.c | 8 ++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/bootstrap/lib.h b/bootstrap/lib.h index 7189df2..2ccc384 100644 --- a/bootstrap/lib.h +++ b/bootstrap/lib.h @@ -384,6 +384,14 @@ may_be_unused fn Hash64 hash_bytes(String bytes) return result; } +may_be_unused fn Hash32 hash64_to_hash32(Hash64 hash64) +{ + Hash32 low = hash64 & 0xffff; + Hash32 high = (hash64 >> 32) & 0xffff; + Hash32 result = (high << 16) | low; + return result; +} + #if LINK_LIBC == 0 #ifdef __linux__ may_be_unused fn forceinline long syscall0(long n) diff --git a/bootstrap/main.c b/bootstrap/main.c index dad07ec..e3dbc83 100644 --- a/bootstrap/main.c +++ b/bootstrap/main.c @@ -153,7 +153,9 @@ fn StringMapPut string_map_get(StringMap* map, String key) { u32 value = 0; auto long_hash = hash_bytes(key); - auto hash = (Hash32)long_hash; + static_assert(sizeof(long_hash) == sizeof(u64)); + auto hash = hash64_to_hash32(long_hash); + static_assert(sizeof(hash) == sizeof(u32)); assert(hash); auto index = hash & (map->capacity - 1); auto slot = string_map_find_slot(map, index, key); @@ -174,7 +176,9 @@ fn StringMapPut string_map_get(StringMap* map, String key) fn StringMapPut string_map_put(StringMap* map, Arena* arena, String key, u32 value) { auto long_hash = hash_bytes(key); - auto hash = (Hash32)long_hash; + static_assert(sizeof(long_hash) == sizeof(u64)); + auto hash = hash64_to_hash32(long_hash); + static_assert(sizeof(hash) == sizeof(u32)); assert(hash); auto index = hash & (map->capacity - 1); auto slot = string_map_find_slot(map, index, key);