Skip to content

Commit

Permalink
Implement WriterTo
Browse files Browse the repository at this point in the history
Avoids allocation/copy when writing byteview to a writer.
  • Loading branch information
luciferous committed Mar 2, 2017
1 parent 72d04f9 commit f81960b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
15 changes: 15 additions & 0 deletions byteview.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
5 changes: 5 additions & 0 deletions byteview_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package groupcache

import (
"bytes"
"fmt"
"io"
"io/ioutil"
Expand Down Expand Up @@ -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)
}
}
}
}
Expand Down

0 comments on commit f81960b

Please sign in to comment.