runtime: implement memhash

This function is used by the hash/maphash package.

Unfortunately, I couldn't get the hash/maphash package to pass tests
because it's too slow. I think it hits the quadratic complexity of the
current map implementation.
This commit is contained in:
Ayke van Laethem
2022-03-02 18:16:05 +01:00
committed by Ron Evans
parent 4c28f1b875
commit b9c0aa77bf
2 changed files with 43 additions and 22 deletions
+34
View File
@@ -3,6 +3,8 @@ package runtime
// This file implements various core algorithms used in the runtime package and
// standard library.
import "unsafe"
// This function is used by hash/maphash.
func fastrand() uint32 {
xorshift32State = xorshift32(xorshift32State)
@@ -20,3 +22,35 @@ func xorshift32(x uint32) uint32 {
x ^= x << 9
return x
}
// This function is used by hash/maphash.
func memhash(p unsafe.Pointer, seed, s uintptr) uintptr {
if unsafe.Sizeof(uintptr(0)) > 4 {
return seed ^ uintptr(hash64(p, s))
}
return seed ^ uintptr(hash32(p, s))
}
// 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) uint32 {
var result uint32 = 2166136261 // 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) uint64 {
var result uint64 = 14695981039346656037 // 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
}