| 1 |
package buffer |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
"testing" |
| 8 |
|
| 9 |
"github.com/tdewolff/test" |
| 10 |
) |
| 11 |
|
| 12 |
func TestReader(t *testing.T) { |
| 13 |
s := []byte("abcde") |
| 14 |
r := NewReader(s) |
| 15 |
test.T(t, r.Len(), 5, "len") |
| 16 |
test.Bytes(t, r.Bytes(), s, "reader must return bytes stored") |
| 17 |
|
| 18 |
buf := make([]byte, 3) |
| 19 |
n, err := r.Read(buf) |
| 20 |
test.T(t, err, nil, "error") |
| 21 |
test.That(t, n == 3, "first read must read 3 characters") |
| 22 |
test.Bytes(t, buf, []byte("abc"), "first read must match 'abc'") |
| 23 |
|
| 24 |
n, err = r.Read(buf) |
| 25 |
test.T(t, err, nil, "error") |
| 26 |
test.That(t, n == 2, "second read must read 2 characters") |
| 27 |
test.Bytes(t, buf[:n], []byte("de"), "second read must match 'de'") |
| 28 |
|
| 29 |
n, err = r.Read(buf) |
| 30 |
test.T(t, err, io.EOF, "error") |
| 31 |
test.That(t, n == 0, "third read must read 0 characters") |
| 32 |
|
| 33 |
n, err = r.Read(nil) |
| 34 |
test.T(t, err, io.EOF, "error") |
| 35 |
test.That(t, n == 0, "read to nil buffer must return 0 characters read") |
| 36 |
|
| 37 |
r.Reset() |
| 38 |
n, err = r.Read(buf) |
| 39 |
test.T(t, err, nil, "error") |
| 40 |
test.That(t, n == 3, "read after reset must read 3 characters") |
| 41 |
test.Bytes(t, buf, []byte("abc"), "read after reset must match 'abc'") |
| 42 |
} |
| 43 |
|
| 44 |
func ExampleNewReader() { |
| 45 |
r := NewReader([]byte("Lorem ipsum")) |
| 46 |
w := &bytes.Buffer{} |
| 47 |
io.Copy(w, r) |
| 48 |
fmt.Println(w.String()) |
| 49 |
// Output: Lorem ipsum |
| 50 |
} |