2 netstring -- netstring format serialization library
3 Copyright (C) 2015-2023 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
35 // Pay attention that bufio.Reader is used to read from it.
36 func NewReader(r io.Reader) *Reader {
37 return &Reader{r: bufio.NewReader(r), eof: true}
40 // Parse netstring prefix. It returns data length.
41 // After this method you have to call either Read() or Discard().
42 // io.EOF is returned when underlying reader has no data anymore.
43 func (r *Reader) Next() (uint64, error) {
45 return 0, errors.New("current chunk is unread")
47 lenRaw, err := r.r.ReadSlice(':')
49 return 0, fmt.Errorf("netstring header: %w", err)
51 lenRaw = lenRaw[:len(lenRaw)-1]
52 if len(lenRaw) > 1 && lenRaw[0] == '0' {
53 return 0, errors.New("netstring header: leading zero")
55 size, err := strconv.ParseUint(string(lenRaw), 10, 64)
57 return 0, fmt.Errorf("netstring header: %w", err)
62 err = r.checkTerminator()
70 func (r *Reader) checkTerminator() error {
71 b, err := r.r.ReadByte()
73 return fmt.Errorf("netstring terminator: %w", err)
76 return errors.New("netstring terminator: not found")
81 // Read current netstring chunk.
82 // This method must be called after Next().
83 // Terminator check and error raising are performed only at the end.
84 func (r *Reader) Read(buf []byte) (n int, err error) {
88 if uint64(len(buf)) > r.left {
91 n, err = r.r.Read(buf)
94 err = r.checkTerminator()
102 // Discard remaining bytes in the chunk, possibly fully skipping it.
103 // This method must be called after Next().
104 func (r *Reader) Discard() (err error) {
105 _, err = r.r.Discard(int(r.left))
109 err = r.checkTerminator()