aboutsummaryrefslogtreecommitdiff
path: root/src/bufio/bufio.go
diff options
context:
space:
mode:
authorBrad Fitzpatrick <bradfitz@golang.org>2015-01-02 10:02:15 -0800
committerBrad Fitzpatrick <bradfitz@golang.org>2015-01-07 06:37:57 +0000
commitee2ecc4552d8fd2b29be29aed1fe81dca0df60f9 (patch)
tree1300cd6fabb2c8a89ef8ad554e40e567d8a3835e /src/bufio/bufio.go
parent5f179c7cef24c74627632ca1b9df8d5ea3912ace (diff)
downloadgo-ee2ecc4552d8fd2b29be29aed1fe81dca0df60f9.tar.xz
bufio: add Reader.Discard
Reader.Discard is the complement to Peek. It discards the next n bytes of input. We already have Reader.Buffered to see how many bytes of data are sitting available in memory, and Reader.Peek to get that that buffer directly. But once you're done with the Peek'd data, you can't get rid of it, other than Reading it. Both Read and io.CopyN(ioutil.Discard, bufReader, N) are relatively slow. People instead resort to multiple blind ReadByte calls, just to advance the internal b.r variable. I've wanted this previously, several people have asked for it in the past on golang-nuts/dev, and somebody just asked me for it again in a private email. There are a few places in the standard library we'd use it too. Change-Id: I85dfad47704a58bd42f6867adbc9e4e1792bc3b0 Reviewed-on: https://go-review.googlesource.com/2260 Reviewed-by: Russ Cox <rsc@golang.org>
Diffstat (limited to 'src/bufio/bufio.go')
-rw-r--r--src/bufio/bufio.go33
1 files changed, 33 insertions, 0 deletions
diff --git a/src/bufio/bufio.go b/src/bufio/bufio.go
index d3c68fe6fe..dbbe80e4c2 100644
--- a/src/bufio/bufio.go
+++ b/src/bufio/bufio.go
@@ -144,6 +144,39 @@ func (b *Reader) Peek(n int) ([]byte, error) {
return b.buf[b.r : b.r+n], err
}
+// Discard skips the next n bytes, returning the number of bytes discarded.
+//
+// If Discard skips fewer than n bytes, it also returns an error.
+// If 0 <= n <= b.Buffered(), Discard is guaranteed to succeed without
+// reading from the underlying io.Reader.
+func (b *Reader) Discard(n int) (discarded int, err error) {
+ if n < 0 {
+ return 0, ErrNegativeCount
+ }
+ if n == 0 {
+ return
+ }
+ remain := n
+ for {
+ skip := b.Buffered()
+ if skip == 0 {
+ b.fill()
+ skip = b.Buffered()
+ }
+ if skip > remain {
+ skip = remain
+ }
+ b.r += skip
+ remain -= skip
+ if remain == 0 {
+ return n, nil
+ }
+ if b.err != nil {
+ return n - remain, b.readErr()
+ }
+ }
+}
+
// Read reads data into p.
// It returns the number of bytes read into p.
// It calls Read at most once on the underlying Reader,