Merge pull request #80 from luciferous/writeto

Implement WriterTo
This commit is contained in:
Brad Fitzpatrick 2017-04-20 20:56:42 -04:00 committed by GitHub
commit b710c8433b
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 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 package groupcache
import ( import (
"bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil" "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 { 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) 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)
}
} }
} }
} }