github.com/chain5j/chain5j-pkg@v1.0.7/collection/maps/shardedmap/util.go (about)

     1  package shardedmap
     2  
     3  import (
     4  	"runtime"
     5  	"unsafe"
     6  )
     7  
     8  //nolint:gochecknoglobals
     9  var defaultShards = runtime.NumCPU() * 16 // github.com/tidwall/shardmap recommendation
    10  
    11  // Adapted from https://github.com/dgraph-io/ristretto/blob/master/z/rtutil.go
    12  //
    13  // MIT License
    14  // Copyright (c) 2019 Ewan Chou
    15  //
    16  // Not copying the whole thing as this repo itself is under MIT License. If
    17  // that's considered a violation, just message me.
    18  
    19  //go:noescape
    20  //go:linkname rtmemhash runtime.memhash
    21  func rtmemhash(p unsafe.Pointer, h, s uintptr) uintptr
    22  
    23  type stringStruct struct {
    24  	str unsafe.Pointer
    25  	len int
    26  }
    27  
    28  // memHash is the hash function used by go map, it utilizes available hardware instructions(behaves
    29  // as aeshash if aes instruction is available).
    30  // NOTE: The hash seed changes for every process. So, this cannot be used as a persistent hash.
    31  func memHash(data []byte) uint64 {
    32  	ss := (*stringStruct)(unsafe.Pointer(&data))
    33  	return uint64(rtmemhash(ss.str, 0, uintptr(ss.len)))
    34  }
    35  
    36  // memHashString is the hash function used by go map, it utilizes available hardware instructions
    37  // (behaves as aeshash if aes instruction is available).
    38  // NOTE: The hash seed changes for every process. So, this cannot be used as a persistent hash.
    39  func memHashString(str string) uint64 {
    40  	ss := (*stringStruct)(unsafe.Pointer(&str))
    41  	return uint64(rtmemhash(ss.str, 0, uintptr(ss.len)))
    42  }