OLD | NEW |
1 // Copyright 2009 The Go Authors. All rights reserved. | 1 // Copyright 2009 The Go Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style | 2 // Use of this source code is governed by a BSD-style |
3 // license that can be found in the LICENSE file. | 3 // license that can be found in the LICENSE file. |
4 | 4 |
5 package strings | 5 package strings |
6 | 6 |
7 import ( | 7 import ( |
8 "errors" | 8 "errors" |
9 "io" | 9 "io" |
10 "unicode/utf8" | 10 "unicode/utf8" |
11 ) | 11 ) |
12 | 12 |
13 // A Reader implements the io.Reader, io.ReaderAt, io.Seeker, | 13 // A Reader implements the io.Reader, io.ReaderAt, io.Seeker, |
14 // io.ByteScanner, and io.RuneScanner interfaces by reading | 14 // io.ByteScanner, and io.RuneScanner interfaces by reading |
15 // from a string. | 15 // from a string. |
16 type Reader struct { | 16 type Reader struct { |
17 s string | 17 s string |
18 i int // current reading index | 18 i int // current reading index |
19 prevRune int // index of previous rune; or < 0 | 19 prevRune int // index of previous rune; or < 0 |
20 } | 20 } |
21 | 21 |
22 // Len returns the number of bytes of the unread portion of the | 22 // Len returns the number of bytes of the unread portion of the |
23 // string. | 23 // string. |
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
113 if abs < 0 { | 113 if abs < 0 { |
114 return 0, errors.New("strings: negative position") | 114 return 0, errors.New("strings: negative position") |
115 } | 115 } |
116 if abs >= 1<<31 { | 116 if abs >= 1<<31 { |
117 return 0, errors.New("strings: position out of range") | 117 return 0, errors.New("strings: position out of range") |
118 } | 118 } |
119 r.i = int(abs) | 119 r.i = int(abs) |
120 return abs, nil | 120 return abs, nil |
121 } | 121 } |
122 | 122 |
| 123 // WriteTo implements the io.WriterTo interface. |
| 124 func (r *Reader) WriteTo(w io.Writer) (n int64, err error) { |
| 125 r.prevRune = -1 |
| 126 if r.i >= len(r.s) { |
| 127 return 0, io.EOF |
| 128 } |
| 129 s := r.s[r.i:] |
| 130 m, e := io.WriteString(w, s) |
| 131 if m > len(s) { |
| 132 panic("strings.Reader.WriteTo: invalid WriteString count") |
| 133 } |
| 134 r.i += m |
| 135 n = int64(m) |
| 136 if e != nil { |
| 137 return n, e |
| 138 } |
| 139 if m != len(s) { |
| 140 return n, io.ErrShortWrite |
| 141 } |
| 142 return n, nil |
| 143 } |
| 144 |
123 // NewReader returns a new Reader reading from s. | 145 // NewReader returns a new Reader reading from s. |
124 // It is similar to bytes.NewBufferString but more efficient and read-only. | 146 // It is similar to bytes.NewBufferString but more efficient and read-only. |
125 func NewReader(s string) *Reader { return &Reader{s, 0, -1} } | 147 func NewReader(s string) *Reader { return &Reader{s, 0, -1} } |
OLD | NEW |