]> Cypherpunks.ru repositories - netstring.git/blobdiff - r.go
Do not require explicit Read for zero length
[netstring.git] / r.go
diff --git a/r.go b/r.go
index 7a6d28452521f0f03eb5a09822ab1e8c8b69092a..098ee49be485cb37a10e420c5fce7c03c6405a5d 100644 (file)
--- a/r.go
+++ b/r.go
@@ -19,8 +19,8 @@ package netstring
 
 import (
        "bufio"
-       "bytes"
        "errors"
+       "fmt"
        "io"
        "strconv"
 )
@@ -44,33 +44,36 @@ func (r *Reader) Next() (uint64, error) {
        if !r.eof {
                return 0, errors.New("current chunk is unread")
        }
-       p, _ := r.r.Peek(21)
-       if len(p) == 0 {
-               return 0, io.EOF
+       lenRaw, err := r.r.ReadSlice(':')
+       if err != nil {
+               return 0, fmt.Errorf("netstring header: %w", err)
        }
-       idx := bytes.IndexByte(p, ':')
-       if idx == -1 {
-               return 0, errors.New("no length separator found")
+       lenRaw = lenRaw[:len(lenRaw)-1]
+       if len(lenRaw) > 1 && lenRaw[0] == '0' {
+               return 0, errors.New("netstring header: leading zero")
        }
-       size, err := strconv.ParseUint(string(p[:idx]), 10, 64)
+       size, err := strconv.ParseUint(string(lenRaw), 10, 64)
        if err != nil {
-               return 0, err
-       }
-       if _, err = r.r.Discard(idx + 1); err != nil {
-               return 0, err
+               return 0, fmt.Errorf("netstring header: %w", err)
        }
        r.left = size
        r.eof = false
-       return size, nil
+       if r.left == 0 {
+               err = r.checkTerminator()
+               if err == nil {
+                       r.eof = true
+               }
+       }
+       return size, err
 }
 
 func (r *Reader) checkTerminator() error {
        b, err := r.r.ReadByte()
        if err != nil {
-               return err
+               return fmt.Errorf("netstring terminator: %w", err)
        }
        if b != ',' {
-               return errors.New("no terminator found")
+               return errors.New("netstring terminator: not found")
        }
        return nil
 }