mirror of
https://github.com/mailgun/groupcache.git
synced 2024-11-16 14:10:04 +00:00
Implement WriterTo
Avoids allocation/copy when writing byteview to a writer.
This commit is contained in:
parent
72d04f9fcd
commit
f81960bea5
15
byteview.go
15
byteview.go
@ -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
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user