-/*
-netstring -- netstring format serialization library
-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
-the Free Software Foundation, version 3 of the License.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
-*/
+// netstring -- netstring format serialization library
+// Copyright (C) 2015-2024 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
+// the Free Software Foundation, version 3 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
package netstring
import (
"bufio"
"errors"
+ "fmt"
"io"
"strconv"
)
}
lenRaw, err := r.r.ReadSlice(':')
if err != nil {
- return 0, err
+ return 0, fmt.Errorf("netstring header: %w", err)
}
- size, err := strconv.ParseUint(string(lenRaw[:len(lenRaw)-1]), 10, 64)
+ 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(lenRaw), 10, 64)
if 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
}