Commit d232453e authored by Luke Champine's avatar Luke Champine

ReadPrefix should not obscure errors

parent c6ccf5ef
package encoding
import (
"errors"
"fmt"
"io"
)
var (
errNoData = errors.New("no data")
errBadPrefix = errors.New("could not read full length prefix")
)
// ReadPrefix reads an 8-byte length prefixes, followed by the number of bytes
// specified in the prefix. The operation is aborted if the prefix exceeds a
// specified maximum length.
func ReadPrefix(r io.Reader, maxLen uint64) ([]byte, error) {
prefix := make([]byte, 8)
if n, err := io.ReadFull(r, prefix); n == 0 {
if err == nil {
err = errNoData
}
if _, err := io.ReadFull(r, prefix); err != nil {
return nil, err
} else if err != nil {
return nil, errBadPrefix
}
dataLen := DecUint64(prefix)
if dataLen > maxLen {
......
......@@ -45,16 +45,14 @@ func TestReadPrefix(t *testing.T) {
// less than 8 bytes
b.Write([]byte{1, 2, 3})
_, err = ReadPrefix(b, 3)
if err != errBadPrefix {
t.Error("expected errBadPrefix, got", err)
if err != io.ErrUnexpectedEOF {
t.Error("expected unexpected EOF, got", err)
}
// exceed maxLen
b.Write(EncUint64(4))
_, err = ReadPrefix(b, 3)
if err == nil {
t.Error("expected errBadPrefix, got nil")
} else if err.Error() != "length 4 exceeds maxLen of 3" {
if err == nil || err.Error() != "length 4 exceeds maxLen of 3" {
t.Error("expected maxLen error, got", err)
}
......@@ -91,10 +89,8 @@ func TestReadObject(t *testing.T) {
b.Write(EncUint64(3))
b.WriteString("foo") // strings need an additional length prefix
err = ReadObject(b, &obj, 3)
if err == nil {
t.Error("expected err, got nil")
} else if err.Error() != "could not decode type string: "+errBadPrefix.Error() {
t.Error("expected errBadPrefix, got", err)
if err == nil || err.Error() != "could not decode type string: "+io.ErrUnexpectedEOF.Error() {
t.Error("expected unexpected EOF, got", err)
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment