aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRuss Cox <rsc@golang.org>2010-04-26 10:02:01 -0700
committerRuss Cox <rsc@golang.org>2010-04-26 10:02:01 -0700
commit78551a9b434e0d912d724e17c7957c98087e9a2d (patch)
tree991016b01fc91352a30dfe9442955648514979ef
parent9f69ab39f0fa3ed2b35c7c23aff060e91f2682ac (diff)
downloadgo-78551a9b434e0d912d724e17c7957c98087e9a2d.tar.gz
go-78551a9b434e0d912d724e17c7957c98087e9a2d.zip
bytes: add Next method to Buffer, simplify Read.
R=r CC=golang-dev https://golang.org/cl/980043
-rw-r--r--src/pkg/bytes/buffer.go18
-rw-r--r--src/pkg/bytes/buffer_test.go35
2 files changed, 47 insertions, 6 deletions
diff --git a/src/pkg/bytes/buffer.go b/src/pkg/bytes/buffer.go
index faccca3be0..7a996c4caf 100644
--- a/src/pkg/bytes/buffer.go
+++ b/src/pkg/bytes/buffer.go
@@ -196,17 +196,23 @@ func (b *Buffer) Read(p []byte) (n int, err os.Error) {
b.Truncate(0)
return 0, os.EOF
}
- m := b.Len()
- n = len(p)
+ n = copy(p, b.buf[b.off:])
+ b.off += n
+ return
+}
+// Next returns a slice containing the next n bytes from the buffer,
+// advancing the buffer as if the bytes had been returned by Read.
+// If there are fewer than n bytes in the buffer, Next returns the entire buffer.
+// The slice is only valid until the next call to a read or write method.
+func (b *Buffer) Next(n int) []byte {
+ m := b.Len()
if n > m {
- // more bytes requested than available
n = m
}
-
- copy(p, b.buf[b.off:b.off+n])
+ data := b.buf[b.off : b.off+n]
b.off += n
- return n, err
+ return data
}
// ReadByte reads and returns the next byte from the buffer.
diff --git a/src/pkg/bytes/buffer_test.go b/src/pkg/bytes/buffer_test.go
index d24bbbe4b8..bc696f4b5e 100644
--- a/src/pkg/bytes/buffer_test.go
+++ b/src/pkg/bytes/buffer_test.go
@@ -264,6 +264,7 @@ func TestWriteTo(t *testing.T) {
}
}
+
func TestRuneIO(t *testing.T) {
const NRune = 1000
// Built a test array while we write the data
@@ -297,3 +298,37 @@ func TestRuneIO(t *testing.T) {
}
}
}
+
+
+func TestNext(t *testing.T) {
+ b := []byte{0, 1, 2, 3, 4}
+ tmp := make([]byte, 5)
+ for i := 0; i <= 5; i++ {
+ for j := i; j <= 5; j++ {
+ for k := 0; k <= 6; k++ {
+ // 0 <= i <= j <= 5; 0 <= k <= 6
+ // Check that if we start with a buffer
+ // of length j at offset i and ask for
+ // Next(k), we get the right bytes.
+ buf := NewBuffer(b[0:j])
+ n, _ := buf.Read(tmp[0:i])
+ if n != i {
+ t.Fatalf("Read %d returned %d", i, n)
+ }
+ bb := buf.Next(k)
+ want := k
+ if want > j-i {
+ want = j - i
+ }
+ if len(bb) != want {
+ t.Fatalf("in %d,%d: len(Next(%d)) == %d", i, j, k, len(bb))
+ }
+ for l, v := range bb {
+ if v != byte(l+i) {
+ t.Fatalf("in %d,%d: Next(%d)[%d] = %d, want %d", i, j, k, l, v, l+i)
+ }
+ }
+ }
+ }
+ }
+}