bufio: add Reader.Size and Writer.Size accessors

Fixes #21343

Change-Id: I3582fced902592fe12bfa29acf7b40b6e5e554a7
Reviewed-on: https://go-review.googlesource.com/75150
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Robert Griesemer <gri@golang.org>
This commit is contained in:
Brad Fitzpatrick 2017-11-01 19:00:05 +00:00
parent 2da1446bb1
commit 6128ff84f1
3 changed files with 26 additions and 0 deletions

View File

@ -62,6 +62,9 @@ func NewReader(rd io.Reader) *Reader {
return NewReaderSize(rd, defaultBufSize)
}
// Size returns the size of the underlying buffer in bytes.
func (r *Reader) Size() int { return len(r.buf) }
// Reset discards any buffered data, resets all state, and switches
// the buffered reader to read from r.
func (b *Reader) Reset(r io.Reader) {
@ -548,6 +551,9 @@ func NewWriter(w io.Writer) *Writer {
return NewWriterSize(w, defaultBufSize)
}
// Size returns the size of the underlying buffer in bytes.
func (b *Writer) Size() int { return len(b.buf) }
// Reset discards any unflushed buffered data, clears any error, and
// resets b to write its output to w.
func (b *Writer) Reset(w io.Writer) {

View File

@ -1418,6 +1418,24 @@ func TestReaderDiscard(t *testing.T) {
}
func TestReaderSize(t *testing.T) {
if got, want := NewReader(nil).Size(), DefaultBufSize; got != want {
t.Errorf("NewReader's Reader.Size = %d; want %d", got, want)
}
if got, want := NewReaderSize(nil, 1234).Size(), 1234; got != want {
t.Errorf("NewReaderSize's Reader.Size = %d; want %d", got, want)
}
}
func TestWriterSize(t *testing.T) {
if got, want := NewWriter(nil).Size(), DefaultBufSize; got != want {
t.Errorf("NewWriter's Writer.Size = %d; want %d", got, want)
}
if got, want := NewWriterSize(nil, 1234).Size(), 1234; got != want {
t.Errorf("NewWriterSize's Writer.Size = %d; want %d", got, want)
}
}
// An onlyReader only implements io.Reader, no matter what other methods the underlying implementation may have.
type onlyReader struct {
io.Reader

View File

@ -11,6 +11,8 @@ import (
var IsSpace = isSpace
const DefaultBufSize = defaultBufSize
func (s *Scanner) MaxTokenSize(n int) {
if n < utf8.UTFMax || n > 1e9 {
panic("bad max token size")