Merge pull request #33 from ledgerwatch/rlp_u32

rlp.U32 method
This commit is contained in:
Alex Sharov 2021-08-15 19:03:29 +07:00 committed by GitHub
commit 99d12ccdb1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 80 additions and 0 deletions

View File

@ -127,6 +127,28 @@ func U64(payload []byte, pos int) (int, uint64, error) {
return dataPos + dataLen, r, nil
}
// U32 parses uint64 number from given payload at given position
func U32(payload []byte, pos int) (int, uint32, error) {
dataPos, dataLen, isList, err := Prefix(payload, pos)
if err != nil {
return 0, 0, err
}
if isList {
return 0, 0, fmt.Errorf("uint32 must be a string, not isList")
}
if dataLen > 4 {
return 0, 0, fmt.Errorf("uint32 must not be more than 4 bytes long, got %d", dataLen)
}
if dataLen > 0 && payload[dataPos] == 0 {
return 0, 0, fmt.Errorf("integer encoding for RLP must not have leading zeros: %x", payload[dataPos:dataPos+dataLen])
}
var r uint32
for _, b := range payload[dataPos : dataPos+dataLen] {
r = (r << 8) | uint32(b)
}
return dataPos + dataLen, r, nil
}
// U256 parses uint256 number from given payload at given position
func U256(payload []byte, pos int, x *uint256.Int) (int, error) {
dataPos, dataLen, err := String(payload, pos)

58
rlp/parse_test.go Normal file
View File

@ -0,0 +1,58 @@
package rlp
import (
"encoding/hex"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func decodeHex(in string) []byte {
payload, err := hex.DecodeString(in)
if err != nil {
panic(err)
}
return payload
}
var parseU64Tests = []struct {
payload []byte
expectPos int
expectRes uint64
expectErr error
}{
{payload: decodeHex("820400"), expectPos: 3, expectRes: 1024},
{payload: decodeHex("07"), expectPos: 1, expectRes: 7},
}
var parseU32Tests = []struct {
payload []byte
expectPos int
expectRes uint32
expectErr error
}{
{payload: decodeHex("820400"), expectPos: 3, expectRes: 1024},
{payload: decodeHex("07"), expectPos: 1, expectRes: 7},
}
func TestPrimitives(t *testing.T) {
for i, tt := range parseU64Tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
assert := assert.New(t)
pos, res, err := U64(tt.payload, 0)
assert.NoError(err)
assert.Equal(tt.expectPos, pos)
assert.Equal(tt.expectRes, res)
})
}
for i, tt := range parseU32Tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
assert := assert.New(t)
pos, res, err := U32(tt.payload, 0)
assert.NoError(err)
assert.Equal(tt.expectPos, pos)
assert.Equal(tt.expectRes, res)
})
}
}