internal: create package for unsafe bytes convertion (#8733)
Co-authored-by: Alessio Treglia <alessio@tendermint.com>
This commit is contained in:
co-authored by
Alessio Treglia
parent
0792db78b8
commit
5f2b90c3c7
+2
-11
@@ -4,10 +4,9 @@ import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"unsafe"
|
||||
|
||||
"github.com/cosmos/cosmos-sdk/internal/conv"
|
||||
"github.com/cosmos/cosmos-sdk/types/errors"
|
||||
)
|
||||
|
||||
@@ -21,7 +20,7 @@ type Addressable interface {
|
||||
// Hash creates a new address from address type and key
|
||||
func Hash(typ string, key []byte) []byte {
|
||||
hasher := sha256.New()
|
||||
hasher.Write(unsafeStrToByteArray(typ))
|
||||
hasher.Write(conv.UnsafeStrToBytes(typ))
|
||||
th := hasher.Sum(nil)
|
||||
|
||||
hasher.Reset()
|
||||
@@ -63,11 +62,3 @@ func Module(moduleName string, key []byte) []byte {
|
||||
mKey := append([]byte(moduleName), 0)
|
||||
return Hash("module", append(mKey, key...))
|
||||
}
|
||||
|
||||
// unsafeStrToByteArray uses unsafe to convert string into byte array. Returned bytes
|
||||
// must not be altered after this function is called as it will cause a segmentation fault.
|
||||
func unsafeStrToByteArray(s string) []byte {
|
||||
var buf = *(*[]byte)(unsafe.Pointer(&s))
|
||||
(*reflect.SliceHeader)(unsafe.Pointer(&buf)).Cap = len(s)
|
||||
return buf
|
||||
}
|
||||
|
||||
@@ -2,9 +2,7 @@ package address
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/suite"
|
||||
@@ -77,23 +75,6 @@ func (suite *AddressSuite) TestModule() {
|
||||
assert.NotEqual(addr2, addr3, "changing key must change address")
|
||||
}
|
||||
|
||||
func unsafeConvertABC() []byte {
|
||||
return unsafeStrToByteArray("abc")
|
||||
}
|
||||
|
||||
func (suite *AddressSuite) TestUnsafeStrToBytes() {
|
||||
// we convert in other function to trigger GC. We want to check that
|
||||
// the underlying array in []bytes is accessible after GC will finish swapping.
|
||||
for i := 0; i < 5; i++ {
|
||||
b := unsafeConvertABC()
|
||||
runtime.GC()
|
||||
<-time.NewTimer(2 * time.Millisecond).C
|
||||
b2 := append(b, 'd')
|
||||
suite.Equal("abc", string(b))
|
||||
suite.Equal("abcd", string(b2))
|
||||
}
|
||||
}
|
||||
|
||||
type addrMock struct {
|
||||
Addr []byte
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user