Skip to content

Commit

Permalink
Improve readNBytes
Browse files Browse the repository at this point in the history
  • Loading branch information
gagliardetto committed Aug 28, 2022
1 parent bce3c06 commit cafc7f3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
15 changes: 6 additions & 9 deletions decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,22 +274,19 @@ type peekAbleByteReader interface {
Peek(n int) ([]byte, error)
}

func readNBytes(n int, reader peekAbleByteReader) ([]byte, error) {
func readNBytes(n int, reader *Decoder) ([]byte, error) {
if n == 0 {
return make([]byte, 0), nil
}
if n < 0 || n > 0x7FFF_FFFF {
return nil, fmt.Errorf("invalid length n: %v", n)
}
buf := make([]byte, n)
for i := 0; i < n; i++ {
b, err := reader.ReadByte()
if err != nil {
return nil, err
}
buf[i] = b
if reader.pos+n > len(reader.data) {
return nil, fmt.Errorf("not enough data: %d bytes missing", reader.pos+n-len(reader.data))
}
return buf, nil
out := reader.data[reader.pos : reader.pos+n]
reader.pos += n
return out, nil
}

func discardNBytes(n int, reader *Decoder) error {
Expand Down
20 changes: 20 additions & 0 deletions decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1174,6 +1174,26 @@ func Test_Decode_custom(t *testing.T) {
})
}

func Test_ReadNBytes(t *testing.T) {
{
b1 := []byte{123, 99, 88, 77, 66, 55, 44, 33, 22, 11}
b2 := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
buf := concatByteSlices(
b1,
b2,
)
decoder := NewBinDecoder(buf)

got, err := decoder.ReadNBytes(10)
require.NoError(t, err)
require.Equal(t, b1, got)

got, err = decoder.ReadNBytes(10)
require.NoError(t, err)
require.Equal(t, b2, got)
}
}

func Test_Decode_readArrayOfUint(t *testing.T) {
{
{
Expand Down

0 comments on commit cafc7f3

Please sign in to comment.