2 netstring -- netstring format serialization library
3 Copyright (C) 2015-2022 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")
51 idx := bytes.IndexByte(p, ':')
53 return 0, errors.New("no length separator found")
55 size, err := strconv.ParseUint(string(p[:idx]), 10, 64)
59 if _, err = r.r.Discard(idx + 1); err != nil {
67 func (r *Reader) checkTerminator() error {
68 b, err := r.r.ReadByte()
73 return errors.New("no terminator found")
78 // Read current netstring chunk.
79 // This method must be called after Next().
80 // Terminator check and error raising are performed only at the end.
81 func (r *Reader) Read(buf []byte) (n int, err error) {
85 if uint64(len(buf)) > r.left {
88 n, err = r.r.Read(buf)
91 err = r.checkTerminator()
99 // Discard remaining bytes in the chunk, possibly fully skipping it.
100 // This method must be called after Next().
101 func (r *Reader) Discard() (err error) {
102 _, err = r.r.Discard(int(r.left))
106 err = r.checkTerminator()