github.com/tursom/GoCollections@v0.3.10/lang/Hash.go (about) 1 /* 2 * Copyright (c) 2022 tursom. All rights reserved. 3 * Use of this source code is governed by a GPL-3 4 * license that can be found in the LICENSE file. 5 */ 6 7 package lang 8 9 import ( 10 "unsafe" 11 ) 12 13 //goland:noinspection GoVetUnsafePointer 14 func HashAddr[V any](v *V) int32 { 15 p := uintptr(unsafe.Pointer(v)) 16 remain := int32(unsafe.Sizeof(*v)) 17 hash := int32(0) 18 for remain-4 >= 0 { 19 remain -= 4 20 hash = hash*31 ^ *(*int32)(unsafe.Pointer(p)) 21 p += 4 22 } 23 for remain > 0 { 24 hash = hash*31 ^ int32(*(*int8)(unsafe.Pointer(p))) 25 p++ 26 remain-- 27 } 28 29 return hash 30 } 31 32 func Hash32[T any](p *T) int32 { 33 return HashInt32(*(*int32)(unsafe.Pointer(p))) 34 } 35 36 func Hash64[T any](p *T) int32 { 37 i := *(*int64)(unsafe.Pointer(p)) 38 return HashInt64(i) 39 } 40 41 func HashString(str string) int32 { 42 hashCode := int32(0) 43 for _, r := range str { 44 hashCode = 31*hashCode + r 45 } 46 return hashCode 47 }