github.com/rosedblabs/rosedb/v2@v2.3.7-0.20240423093736-a89ea823e5b9/utils/hash.go (about)

     1  package utils
     2  
     3  import (
     4  	_ "runtime"
     5  	"unsafe"
     6  )
     7  
     8  type stringStruct struct {
     9  	str unsafe.Pointer
    10  	len int
    11  }
    12  
    13  //go:noescape
    14  //go:linkname memhash runtime.memhash
    15  func memhash(p unsafe.Pointer, h, s uintptr) uintptr
    16  
    17  // MemHash is the hash function used by go map, it utilizes available hardware instructions(behaves
    18  // as aeshash if aes instruction is available).
    19  // NOTE: The hash seed changes for every process. So, this cannot be used as a persistent hash.
    20  func MemHash(data []byte) uint64 {
    21  	ss := (*stringStruct)(unsafe.Pointer(&data))
    22  	return uint64(memhash(ss.str, 0, uintptr(ss.len)))
    23  }
    24  
    25  // MemHashString is the hash function used by go map, it utilizes available hardware instructions
    26  // (behaves as aeshash if aes instruction is available).
    27  // NOTE: The hash seed changes for every process. So, this cannot be used as a persistent hash.
    28  func MemHashString(str string) uint64 {
    29  	ss := (*stringStruct)(unsafe.Pointer(&str))
    30  	return uint64(memhash(ss.str, 0, uintptr(ss.len)))
    31  }