2
0
mirror of synced 2025-02-23 14:18:13 +00:00

Clarify EOF in message decoding

This commit is contained in:
Matt Joiner 2014-08-22 17:39:18 +10:00
parent 063e02cbfd
commit a2fabedfa2
2 changed files with 12 additions and 6 deletions

View File

@ -109,10 +109,14 @@ type Decoder struct {
MaxLength Integer // TODO: Should this include the length header or not?
}
// io.EOF is returned if the source terminates cleanly on a message boundary.
func (d *Decoder) Decode(msg *Message) (err error) {
var length Integer
err = binary.Read(d.R, binary.BigEndian, &length)
if err != nil {
if err != io.EOF {
err = fmt.Errorf("error reading message length: %s", err)
}
return
}
if length > d.MaxLength {
@ -125,10 +129,13 @@ func (d *Decoder) Decode(msg *Message) (err error) {
msg.Keepalive = false
b := make([]byte, length)
_, err = io.ReadFull(d.R, b)
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
if err != io.ErrUnexpectedEOF {
err = fmt.Errorf("error reading message: %s", err)
}
return
}
r := bytes.NewReader(b)

View File

@ -3,7 +3,6 @@ package peer_protocol
import (
"bufio"
"bytes"
"io"
"strings"
"testing"
)
@ -103,8 +102,8 @@ func TestUnexpectedEOF(t *testing.T) {
MaxLength: 42,
}
err := dec.Decode(msg)
if err != io.ErrUnexpectedEOF {
t.Fatalf("expected ErrUnexpectedEOF decoding %q, got %s", stream, err)
if err == nil {
t.Fatalf("expected an error decoding %q", stream)
}
}
}