]> Sergey Matveev's repositories - btrtrc.git/commitdiff
Clarify EOF in message decoding
authorMatt Joiner <anacrolix@gmail.com>
Fri, 22 Aug 2014 07:39:18 +0000 (17:39 +1000)
committerMatt Joiner <anacrolix@gmail.com>
Fri, 22 Aug 2014 07:39:18 +0000 (17:39 +1000)
peer_protocol/protocol.go
peer_protocol/protocol_test.go

index 87cf38d8b27b97a102d30c19415c7f973bd473c5..db32ac59ce99f31e86dd281b59acda40ba9535ab 100644 (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)
index 807f1dd808bcb980c5985ecab1fe27a5b2b3fb65..d2fc8d4b0a5c4bc3c8be0999d8391e3422f331c0 100644 (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)
                }
        }
 }