github.com/iainanderson83/datastructures@v0.0.4-0.20191103204413-889e20b53bcf/hashmap/memhash.go (about)

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