/* netstring -- netstring format serialization library Copyright (C) 2015 Sergey Matveev 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, either version 3 of the License, or (at your option) any later version. 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 . */ package netstring import ( "bufio" "io" "strconv" ) type Writer struct { writer *bufio.Writer prefix []byte err error } func NewWriter(w io.Writer) *Writer { return &Writer{ writer: bufio.NewWriter(w), prefix: make([]byte, 0, MaxPrefixSize), } } // Write serialized representation of data to the underlying writer. // It returns number of serialized data bytes written. func (self *Writer) Write(data []byte) (bytesWritten int, err error) { self.prefix = strconv.AppendUint(self.prefix[:0], uint64(len(data)), 10) self.prefix = append(self.prefix, ':') if _, self.err = self.writer.Write(self.prefix); self.err != nil { return 0, self.err } if _, self.err = self.writer.Write(data); self.err != nil { return 0, self.err } if _, self.err = self.writer.Write([]byte{','}); self.err != nil { return 0, self.err } if self.err = self.writer.Flush(); self.err != nil { return 0, self.err } return len(self.prefix) + len(data) + 1, nil }