1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
13 // A Reader implements the io.Reader, io.ByteScanner, and
14 // io.RuneScanner interfaces by reading from a string.
17 i int // current reading index
18 prevRune int // index of previous rune; or < 0
21 // Len returns the number of bytes of the unread portion of the
23 func (r *Reader) Len() int {
27 func (r *Reader) Read(b []byte) (n int, err error) {
31 n = copy(b, r.s[r.i:])
37 func (r *Reader) ReadByte() (b byte, err error) {
47 // UnreadByte moves the reading position back by one byte.
48 // It is an error to call UnreadByte if nothing has been
50 func (r *Reader) UnreadByte() error {
52 return errors.New("strings.Reader: at beginning of string")
59 // ReadRune reads and returns the next UTF-8-encoded
60 // Unicode code point from the buffer.
61 // If no bytes are available, the error returned is io.EOF.
62 // If the bytes are an erroneous UTF-8 encoding, it
63 // consumes one byte and returns U+FFFD, 1.
64 func (r *Reader) ReadRune() (ch rune, size int, err error) {
69 if c := r.s[r.i]; c < utf8.RuneSelf {
71 return rune(c), 1, nil
73 ch, size = utf8.DecodeRuneInString(r.s[r.i:])
78 // UnreadRune causes the next call to ReadRune to return the same rune
79 // as the previous call to ReadRune.
80 // The last method called on r must have been ReadRune.
81 func (r *Reader) UnreadRune() error {
83 return errors.New("strings.Reader: previous operation was not ReadRune")
90 // NewReader returns a new Reader reading from s.
91 // It is similar to bytes.NewBufferString but more efficient and read-only.
92 func NewReader(s string) *Reader { return &Reader{s, 0, -1} }