]> Cypherpunks.ru repositories - netstring.git/blobdiff - r.go
Wrapped errors
[netstring.git] / r.go
diff --git a/r.go b/r.go
index f5f74dd856428c15939e609d6affac86f7533715..0c65fd41d01d5039c2b9a3e36bbf9cb6e6b3f892 100644 (file)
--- a/r.go
+++ b/r.go
@@ -1,6 +1,6 @@
 /*
 netstring -- netstring format serialization library
-Copyright (C) 2015-2020 Sergey Matveev <stargrave@stargrave.org>
+Copyright (C) 2015-2023 Sergey Matveev <stargrave@stargrave.org>
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
@@ -19,8 +19,8 @@ package netstring
 
 import (
        "bufio"
-       "bytes"
        "errors"
+       "fmt"
        "io"
        "strconv"
 )
@@ -44,20 +44,13 @@ 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
-       }
-       idx := bytes.Index(p, []byte{':'})
-       if idx == -1 {
-               return 0, errors.New("no length separator found")
-       }
-       size, err := strconv.ParseUint(string(p[:idx]), 10, 64)
+       lenRaw, err := r.r.ReadSlice(':')
        if err != nil {
-               return 0, err
+               return 0, fmt.Errorf("netstring header: %w", err)
        }
-       if _, err = r.r.Discard(idx + 1); err != nil {
-               return 0, err
+       size, err := strconv.ParseUint(string(lenRaw[:len(lenRaw)-1]), 10, 64)
+       if err != nil {
+               return 0, fmt.Errorf("netstring header: %w", err)
        }
        r.left = size
        r.eof = false
@@ -67,10 +60,10 @@ func (r *Reader) Next() (uint64, error) {
 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
 }