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.ReaderAt, io.Seeker, io.WriterTo,
14 // io.ByteScanner, and io.RuneScanner interfaces by reading
18 i
int64 // current reading index
19 prevRune
int // index of previous rune; or < 0
22 // Len returns the number of bytes of the unread portion of the
24 func (r
*Reader
) Len() int {
25 if r
.i
>= int64(len(r
.s
)) {
28 return int(int64(len(r
.s
)) - r
.i
)
31 // Size returns the original length of the underlying string.
32 // Size is the number of bytes available for reading via ReadAt.
33 // The returned value is always the same and is not affected by calls
34 // to any other method.
35 func (r
*Reader
) Size() int64 { return int64(len(r
.s
)) }
37 func (r
*Reader
) Read(b
[]byte) (n
int, err error
) {
38 if r
.i
>= int64(len(r
.s
)) {
42 n
= copy(b
, r
.s
[r
.i
:])
47 func (r
*Reader
) ReadAt(b
[]byte, off
int64) (n
int, err error
) {
48 // cannot modify state - see io.ReaderAt
50 return 0, errors
.New("strings.Reader.ReadAt: negative offset")
52 if off
>= int64(len(r
.s
)) {
55 n
= copy(b
, r
.s
[off
:])
62 func (r
*Reader
) ReadByte() (byte, error
) {
64 if r
.i
>= int64(len(r
.s
)) {
72 func (r
*Reader
) UnreadByte() error
{
75 return errors
.New("strings.Reader.UnreadByte: at beginning of string")
81 func (r
*Reader
) ReadRune() (ch rune
, size
int, err error
) {
82 if r
.i
>= int64(len(r
.s
)) {
87 if c
:= r
.s
[r
.i
]; c
< utf8
.RuneSelf
{
89 return rune(c
), 1, nil
91 ch
, size
= utf8
.DecodeRuneInString(r
.s
[r
.i
:])
96 func (r
*Reader
) UnreadRune() error
{
98 return errors
.New("strings.Reader.UnreadRune: previous operation was not ReadRune")
100 r
.i
= int64(r
.prevRune
)
105 // Seek implements the io.Seeker interface.
106 func (r
*Reader
) Seek(offset
int64, whence
int) (int64, error
) {
115 abs
= int64(len(r
.s
)) + offset
117 return 0, errors
.New("strings.Reader.Seek: invalid whence")
120 return 0, errors
.New("strings.Reader.Seek: negative position")
126 // WriteTo implements the io.WriterTo interface.
127 func (r
*Reader
) WriteTo(w io
.Writer
) (n
int64, err error
) {
129 if r
.i
>= int64(len(r
.s
)) {
133 m
, err
:= io
.WriteString(w
, s
)
135 panic("strings.Reader.WriteTo: invalid WriteString count")
139 if m
!= len(s
) && err
== nil {
140 err
= io
.ErrShortWrite
145 // Reset resets the Reader to be reading from s.
146 func (r
*Reader
) Reset(s
string) { *r
= Reader
{s
, 0, -1} }
148 // NewReader returns a new Reader reading from s.
149 // It is similar to bytes.NewBufferString but more efficient and read-only.
150 func NewReader(s
string) *Reader
{ return &Reader
{s
, 0, -1} }