Add ReadRune and WriteRune to bytes.Buffer

The comments mention bufio's WriteRune, which should come next.

R=rsc
CC=golang-dev
https://golang.org/cl/245041
This commit is contained in:
Rob Pike 2010-03-05 11:34:53 -08:00
parent 4b22e1bdb6
commit 0ac5ef70db
2 changed files with 77 additions and 6 deletions

View file

@ -8,6 +8,7 @@ import (
. "bytes"
"rand"
"testing"
"utf8"
)
@ -262,3 +263,37 @@ func TestWriteTo(t *testing.T) {
empty(t, "TestReadFrom (2)", &b, s, make([]byte, len(data)))
}
}
func TestRuneIO(t *testing.T) {
const NRune = 1000
// Built a test array while we write the data
b := make([]byte, utf8.UTFMax*NRune)
var buf Buffer
n := 0
for r := 0; r < NRune; r++ {
size := utf8.EncodeRune(r, b[n:])
nbytes, err := buf.WriteRune(r)
if err != nil {
t.Fatalf("WriteRune(0x%x) error: %s", r, err)
}
if nbytes != size {
t.Fatalf("WriteRune(0x%x) expected %d, got %d", size, nbytes)
}
n += size
}
b = b[0:n]
// Check the resulting bytes
if !Equal(buf.Bytes(), b) {
t.Fatalf("incorrect result from WriteRune: %q not %q", buf.Bytes(), b)
}
// Read it back with ReadRune
for r := 0; r < NRune; r++ {
size := utf8.EncodeRune(r, b)
nr, nbytes, err := buf.ReadRune()
if nr != r || nbytes != size || err != nil {
t.Fatalf("ReadRune(0x%x) got 0x%x,%d not 0x%x,%d (err=%s)", r, nr, nbytes, r, size, err)
}
}
}