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>
diff --git a/src/bufio/bufio.go b/src/bufio/bufio.go
index da94a25..ad9c9f5 100644
--- a/src/bufio/bufio.go
+++ b/src/bufio/bufio.go
@@ -62,6 +62,9 @@
 	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 @@
 	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) {
diff --git a/src/bufio/bufio_test.go b/src/bufio/bufio_test.go
index ef0f6c8..c829d2b 100644
--- a/src/bufio/bufio_test.go
+++ b/src/bufio/bufio_test.go
@@ -1418,6 +1418,24 @@
 
 }
 
+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
diff --git a/src/bufio/export_test.go b/src/bufio/export_test.go
index 3d3bb27..1667f01 100644
--- a/src/bufio/export_test.go
+++ b/src/bufio/export_test.go
@@ -11,6 +11,8 @@
 
 var IsSpace = isSpace
 
+const DefaultBufSize = defaultBufSize
+
 func (s *Scanner) MaxTokenSize(n int) {
 	if n < utf8.UTFMax || n > 1e9 {
 		panic("bad max token size")