writer_test.go 1.4 KB

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