chore: (x/authz) add helpers AppendBytes, ParseByteSlice (#11713)
This commit is contained in:
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/cosmos/cosmos-sdk/types/kv"
|
||||
dbm "github.com/tendermint/tm-db"
|
||||
)
|
||||
|
||||
@@ -106,3 +107,30 @@ func CopyBytes(bz []byte) (ret []byte) {
|
||||
copy(ret, bz)
|
||||
return ret
|
||||
}
|
||||
|
||||
// AppendLengthPrefixedBytes combines the slices of bytes to one slice of bytes.
|
||||
func AppendLengthPrefixedBytes(args ...[]byte) []byte {
|
||||
length := 0
|
||||
for _, v := range args {
|
||||
length += len(v)
|
||||
}
|
||||
res := make([]byte, length)
|
||||
|
||||
length = 0
|
||||
for _, v := range args {
|
||||
copy(res[length:length+len(v)], v)
|
||||
length += len(v)
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// ParseLengthPrefixedBytes panics when store key length is not equal to the given length.
|
||||
func ParseLengthPrefixedBytes(key []byte, startIndex int, sliceLength int) ([]byte, int) {
|
||||
neededLength := startIndex + sliceLength
|
||||
endIndex := neededLength - 1
|
||||
kv.AssertKeyAtLeastLength(key, neededLength)
|
||||
byteSlice := key[startIndex:neededLength]
|
||||
|
||||
return byteSlice, endIndex
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/types/address"
|
||||
)
|
||||
|
||||
type utilsTestSuite struct {
|
||||
@@ -109,3 +110,23 @@ func (s *utilsTestSuite) TestParseTimeBytes() {
|
||||
_, err = sdk.ParseTimeBytes([]byte{})
|
||||
s.Require().Error(err)
|
||||
}
|
||||
|
||||
func (s *utilsTestSuite) TestAppendParseBytes() {
|
||||
test1 := "test1"
|
||||
test2 := "testString2"
|
||||
testByte1 := []byte(test1)
|
||||
testByte2 := []byte(test2)
|
||||
|
||||
combinedBytes := sdk.AppendLengthPrefixedBytes(address.MustLengthPrefix(testByte1), address.MustLengthPrefix(testByte2))
|
||||
testCombineBytes := append([]byte{}, address.MustLengthPrefix(testByte1)...)
|
||||
testCombineBytes = append(testCombineBytes, address.MustLengthPrefix(testByte2)...)
|
||||
s.Require().Equal(combinedBytes, testCombineBytes)
|
||||
|
||||
test1Len, test1LenEndIndex := sdk.ParseLengthPrefixedBytes(combinedBytes, 0, 1)
|
||||
parseTest1, parseTest1EndIndex := sdk.ParseLengthPrefixedBytes(combinedBytes, test1LenEndIndex+1, int(test1Len[0]))
|
||||
s.Require().Equal(testByte1, parseTest1)
|
||||
|
||||
test2Len, test2LenEndIndex := sdk.ParseLengthPrefixedBytes(combinedBytes, parseTest1EndIndex+1, 1)
|
||||
parseTest2, _ := sdk.ParseLengthPrefixedBytes(combinedBytes, test2LenEndIndex+1, int(test2Len[0]))
|
||||
s.Require().Equal(testByte2, parseTest2)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user