aboutsummaryrefslogtreecommitdiff
path: root/src/pkg/strings
diff options
context:
space:
mode:
authorEvan Shaw <chickencha@gmail.com>2012-10-12 14:43:50 +1100
committerRob Pike <r@golang.org>2012-10-12 14:43:50 +1100
commiteae25d430d6d6c40e129c50ed4a931858be8ffb4 (patch)
treee07eb405d280f3a94f7430ec9fcdde865b9655cc /src/pkg/strings
parent06d42690b6ada912bc657435ca4dd962a9413502 (diff)
downloadgo-eae25d430d6d6c40e129c50ed4a931858be8ffb4.tar.xz
bytes, strings: add (*Reader).WriteTo
Fixes #4031. R=golang-dev, bradfitz, remyoudompheng, r, dave CC=golang-dev https://golang.org/cl/6632046
Diffstat (limited to 'src/pkg/strings')
-rw-r--r--src/pkg/strings/reader.go21
-rw-r--r--src/pkg/strings/reader_test.go23
2 files changed, 43 insertions, 1 deletions
diff --git a/src/pkg/strings/reader.go b/src/pkg/strings/reader.go
index 8569805552..98325ce75b 100644
--- a/src/pkg/strings/reader.go
+++ b/src/pkg/strings/reader.go
@@ -10,7 +10,7 @@ import (
"unicode/utf8"
)
-// A Reader implements the io.Reader, io.ReaderAt, io.Seeker,
+// A Reader implements the io.Reader, io.ReaderAt, io.Seeker, io.WriterTo,
// io.ByteScanner, and io.RuneScanner interfaces by reading
// from a string.
type Reader struct {
@@ -120,6 +120,25 @@ func (r *Reader) Seek(offset int64, whence int) (int64, error) {
return abs, nil
}
+// WriteTo implements the io.WriterTo interface.
+func (r *Reader) WriteTo(w io.Writer) (n int64, err error) {
+ r.prevRune = -1
+ if r.i >= len(r.s) {
+ return 0, io.EOF
+ }
+ s := r.s[r.i:]
+ m, err := io.WriteString(w, s)
+ if m > len(s) {
+ panic("strings.Reader.WriteTo: invalid WriteString count")
+ }
+ r.i += m
+ n = int64(m)
+ if m != len(s) && err == nil {
+ err = io.ErrShortWrite
+ }
+ return
+}
+
// NewReader returns a new Reader reading from s.
// It is similar to bytes.NewBufferString but more efficient and read-only.
func NewReader(s string) *Reader { return &Reader{s, 0, -1} }
diff --git a/src/pkg/strings/reader_test.go b/src/pkg/strings/reader_test.go
index a99ae2a0ea..bab91fc719 100644
--- a/src/pkg/strings/reader_test.go
+++ b/src/pkg/strings/reader_test.go
@@ -5,6 +5,7 @@
package strings_test
import (
+ "bytes"
"fmt"
"io"
"os"
@@ -86,3 +87,25 @@ func TestReaderAt(t *testing.T) {
}
}
}
+
+func TestWriteTo(t *testing.T) {
+ const str = "0123456789"
+ for i := 0; i < len(str); i++ {
+ s := str[i:]
+ r := strings.NewReader(s)
+ var b bytes.Buffer
+ n, err := r.WriteTo(&b)
+ if expect := int64(len(s)); n != expect {
+ t.Errorf("got %v; want %v", n, expect)
+ }
+ if err != nil {
+ t.Errorf("got error = %v; want nil", err)
+ }
+ if b.String() != s {
+ t.Errorf("got string %q; want %q", b.String(), s)
+ }
+ if r.Len() != 0 {
+ t.Errorf("reader contains %v bytes; want 0", r.Len())
+ }
+ }
+}