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