github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/aeshash/hash.go (about)

     1  // Copyright 2020 Insolar Network Ltd.
     2  // All rights reserved.
     3  // This material is licensed under the Insolar License version 1.0,
     4  // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md.
     5  
     6  package aeshash
     7  
     8  import (
     9  	"reflect"
    10  	"unsafe"
    11  
    12  	"github.com/insolar/vanilla/longbits"
    13  	"github.com/insolar/vanilla/unsafekit"
    14  )
    15  
    16  func GoMapHash(v longbits.ByteString) uint32 {
    17  	return uint32(ByteStr(v))
    18  }
    19  
    20  func GoMapHashWithSeed(v longbits.ByteString, seed uint32) uint32 {
    21  	return uint32(StrWithSeed(string(v), uint(seed)))
    22  }
    23  
    24  // Hash hashes the given string using the algorithm used by Go's hash tables
    25  func Str(s string) uint {
    26  	return StrWithSeed(s, 0)
    27  }
    28  
    29  func StrWithSeed(s string, seed uint) uint {
    30  	return uint(unsafekit.KeepAliveWhile(unsafe.Pointer(&s), func(p unsafe.Pointer) uintptr {
    31  		sh := (*reflect.StringHeader)(p)
    32  		return hash(sh.Data, sh.Len, seed)
    33  	}))
    34  }
    35  
    36  // Hash hashes the given slice using the algorithm used by Go's hash tables
    37  func Slice(b []byte) uint {
    38  	return SliceWithSeed(b, 0)
    39  }
    40  
    41  func SliceWithSeed(b []byte, seed uint) uint {
    42  	return uint(unsafekit.KeepAliveWhile(unsafe.Pointer(&b), func(p unsafe.Pointer) uintptr {
    43  		sh := (*reflect.SliceHeader)(p)
    44  		return hash(sh.Data, sh.Len, seed)
    45  	}))
    46  }
    47  
    48  func ByteStr(v longbits.ByteString) uint {
    49  	return Str(string(v))
    50  }
    51  
    52  func hash(data uintptr, len int, seed uint) uintptr {
    53  	return aeshash(data, uintptr(seed), uintptr(len))
    54  }
    55  
    56  // pData, hSeed, sLen
    57  func aeshash(p, h, s uintptr) uintptr