Implement WriterTo

Avoids allocation/copy when writing byteview to a writer.
This commit is contained in:
Neuman Vong 2017-02-24 08:27:23 -08:00
parent 72d04f9fcd
commit f81960bea5
2 changed files with 20 additions and 0 deletions

View File

@ -158,3 +158,18 @@ func (v ByteView) ReadAt(p []byte, off int64) (n int, err error) {
}
return
}
// WriteTo implements io.WriterTo on the bytes in v.
func (v ByteView) WriteTo(w io.Writer) (n int64, err error) {
var m int
if v.b != nil {
m, err = w.Write(v.b)
} else {
m, err = io.WriteString(w, v.s)
}
if err == nil && m < v.Len() {
err = io.ErrShortWrite
}
n = int64(m)
return
}

View File

@ -17,6 +17,7 @@ limitations under the License.
package groupcache
import (
"bytes"
"fmt"
"io"
"io/ioutil"
@ -47,6 +48,10 @@ func TestByteView(t *testing.T) {
if got, err := ioutil.ReadAll(io.NewSectionReader(v, 0, int64(len(s)))); err != nil || string(got) != s {
t.Errorf("%s: SectionReader of ReaderAt = %q, %v; want %q", name, got, err, s)
}
var dest bytes.Buffer
if _, err := v.WriteTo(&dest); err != nil || !bytes.Equal(dest.Bytes(), []byte(s)) {
t.Errorf("%s: WriteTo = %q, %v; want %q", name, dest.Bytes(), err, s)
}
}
}
}