Skip to content

Commit

Permalink
Fix #15 (#16)
Browse files Browse the repository at this point in the history
fix ReadString empty

Co-authored-by: Jason Li Dongheng <jason.lidh@shopee.com>
  • Loading branch information
Jason5Lee and Jason Li Dongheng committed Oct 6, 2023
1 parent 3954148 commit 30053c2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
32 changes: 32 additions & 0 deletions decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package binary

import (
"io"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -25,3 +26,34 @@ func TestBinaryDecodeToValueErrors(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, uint32(1), v)
}

type oneByteReader struct {
content []byte
}

// Read method of io.Reader reads *up to* len(buf) bytes.
// It is possible to read LESS, and it can happen when reading a file.
func (r *oneByteReader) Read(buf []byte) (n int, err error) {
if len(r.content) == 0 {
err = io.EOF
return
}

if len(buf) == 0 {
return
}
n = 1
buf[0] = r.content[0]
r.content = r.content[1:]
return
}

func TestDecodeFromReader(t *testing.T) {
data := "data string"
encoded, err := Marshal(data)
assert.NoError(t, err)
decoder := NewDecoder(&oneByteReader{content: encoded})
str, err := decoder.ReadString()
assert.NoError(t, err)
assert.Equal(t, data, str)
}
2 changes: 1 addition & 1 deletion reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ func (r *streamReader) Slice(n int) (buffer []byte, err error) {
buffer = make([]byte, n, n)
}

_, err = r.Read(buffer)
_, err = io.ReadFull(r, buffer)
return
}

Expand Down

0 comments on commit 30053c2

Please sign in to comment.