src/runtime: switch to stronger hash function

Fixes #2713
This commit is contained in:
Damian Gryski
2022-03-09 13:48:32 -08:00
committed by Ron Evans
parent a4599ba539
commit 11e1b2148f
3 changed files with 196 additions and 25 deletions
+3 -25
View File
@@ -3,7 +3,9 @@ package runtime
// This file implements various core algorithms used in the runtime package and
// standard library.
import "unsafe"
import (
"unsafe"
)
// This function is used by hash/maphash.
func fastrand() uint32 {
@@ -30,27 +32,3 @@ func memhash(p unsafe.Pointer, seed, s uintptr) uintptr {
}
return uintptr(hash32(p, s, seed))
}
// Get FNV-1a hash of the given memory buffer.
//
// https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-1a_hash
func hash32(ptr unsafe.Pointer, n uintptr, seed uintptr) uint32 {
var result uint32 = 2166136261 ^ uint32(seed) // FNV offset basis
for i := uintptr(0); i < n; i++ {
c := *(*uint8)(unsafe.Pointer(uintptr(ptr) + i))
result ^= uint32(c) // XOR with byte
result *= 16777619 // FNV prime
}
return result
}
// Also a FNV-1a hash.
func hash64(ptr unsafe.Pointer, n uintptr, seed uintptr) uint64 {
var result uint64 = 14695981039346656037 ^ uint64(seed) // FNV offset basis
for i := uintptr(0); i < n; i++ {
c := *(*uint8)(unsafe.Pointer(uintptr(ptr) + i))
result ^= uint64(c) // XOR with byte
result *= 1099511628211 // FNV prime
}
return result
}