github.com/fufuok/utils@v1.0.10/xsync/util_hash_mapof.go (about)

     1  //go:build go1.18
     2  // +build go1.18
     3  
     4  package xsync
     5  
     6  import (
     7  	"reflect"
     8  	"unsafe"
     9  )
    10  
    11  // makeHasher creates a fast hash function for the given comparable type.
    12  // The only limitation is that the type should not contain interfaces inside
    13  // based on runtime.typehash.
    14  func makeHasher[T comparable]() func(T, uint64) uint64 {
    15  	var zero T
    16  
    17  	if reflect.TypeOf(&zero).Elem().Kind() == reflect.Interface {
    18  		return func(value T, seed uint64) uint64 {
    19  			iValue := any(value)
    20  			i := (*iface)(unsafe.Pointer(&iValue))
    21  			return runtime_typehash64(i.typ, i.word, seed)
    22  		}
    23  	} else {
    24  		var iZero any = zero
    25  		i := (*iface)(unsafe.Pointer(&iZero))
    26  		return func(value T, seed uint64) uint64 {
    27  			return runtime_typehash64(i.typ, unsafe.Pointer(&value), seed)
    28  		}
    29  	}
    30  }