internal: create package for unsafe bytes convertion (#8733)

Co-authored-by: Alessio Treglia <alessio@tendermint.com>
This commit is contained in:
Robert Zaremba
2021-03-01 15:10:22 +00:00
committed by GitHub
co-authored by Alessio Treglia
parent 0792db78b8
commit 5f2b90c3c7
6 changed files with 77 additions and 56 deletions
+2 -11
View File
@@ -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
}
-19
View File
@@ -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
}