diff options
Diffstat (limited to 'libgo/go/strings')
-rw-r--r-- | libgo/go/strings/reader.go | 21 | ||||
-rw-r--r-- | libgo/go/strings/reader_test.go | 23 | ||||
-rw-r--r-- | libgo/go/strings/strings_test.go | 2 |
3 files changed, 44 insertions, 2 deletions
diff --git a/libgo/go/strings/reader.go b/libgo/go/strings/reader.go index 8569805..98325ce 100644 --- a/libgo/go/strings/reader.go +++ b/libgo/go/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/libgo/go/strings/reader_test.go b/libgo/go/strings/reader_test.go index a99ae2a..bab91fc 100644 --- a/libgo/go/strings/reader_test.go +++ b/libgo/go/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()) + } + } +} diff --git a/libgo/go/strings/strings_test.go b/libgo/go/strings/strings_test.go index c271e48..7be41a8 100644 --- a/libgo/go/strings/strings_test.go +++ b/libgo/go/strings/strings_test.go @@ -995,7 +995,7 @@ func TestEqualFold(t *testing.T) { var makeFieldsInput = func() string { x := make([]byte, 1<<20) - // Input is ~10% space, ~10% 2-byte UTF-8, rest ASCII non-space. + // Input is ~10% space, ~10% 2-byte UTF-8, rest ASCII non-space. for i := range x { switch rand.Intn(10) { case 0: |