| 1 |
package buffer |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"testing" |
| 6 |
|
| 7 |
"github.com/tdewolff/test" |
| 8 |
) |
| 9 |
|
| 10 |
func TestWriter(t *testing.T) { |
| 11 |
w := NewWriter(make([]byte, 0, 3)) |
| 12 |
|
| 13 |
test.That(t, w.Len() == 0, "buffer must initially have zero length") |
| 14 |
|
| 15 |
n, _ := w.Write([]byte("abc")) |
| 16 |
test.That(t, n == 3, "first write must write 3 characters") |
| 17 |
test.Bytes(t, w.Bytes(), []byte("abc"), "first write must match 'abc'") |
| 18 |
test.That(t, w.Len() == 3, "buffer must have length 3 after first write") |
| 19 |
|
| 20 |
n, _ = w.Write([]byte("def")) |
| 21 |
test.That(t, n == 3, "second write must write 3 characters") |
| 22 |
test.Bytes(t, w.Bytes(), []byte("abcdef"), "second write must match 'abcdef'") |
| 23 |
|
| 24 |
w.Reset() |
| 25 |
test.Bytes(t, w.Bytes(), []byte(""), "reset must match ''") |
| 26 |
|
| 27 |
n, _ = w.Write([]byte("ghijkl")) |
| 28 |
test.That(t, n == 6, "third write must write 6 characters") |
| 29 |
test.Bytes(t, w.Bytes(), []byte("ghijkl"), "third write must match 'ghijkl'") |
| 30 |
} |
| 31 |
|
| 32 |
func ExampleNewWriter() { |
| 33 |
w := NewWriter(make([]byte, 0, 11)) // initial buffer length is 11 |
| 34 |
w.Write([]byte("Lorem ipsum")) |
| 35 |
fmt.Println(string(w.Bytes())) |
| 36 |
// Output: Lorem ipsum |
| 37 |
} |
| 38 |
|
| 39 |
func ExampleWriter_Reset() { |
| 40 |
w := NewWriter(make([]byte, 0, 11)) // initial buffer length is 10 |
| 41 |
w.Write([]byte("garbage that will be overwritten")) // does reallocation |
| 42 |
w.Reset() |
| 43 |
w.Write([]byte("Lorem ipsum")) |
| 44 |
fmt.Println(string(w.Bytes())) |
| 45 |
// Output: Lorem ipsum |
| 46 |
} |