writer.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package buffer // import "github.com/tdewolff/parse/buffer"
  2. // Writer implements an io.Writer over a byte slice.
  3. type Writer struct {
  4. buf []byte
  5. }
  6. // NewWriter returns a new Writer for a given byte slice.
  7. func NewWriter(buf []byte) *Writer {
  8. return &Writer{
  9. buf: buf,
  10. }
  11. }
  12. // Write writes bytes from the given byte slice and returns the number of bytes written and an error if occurred. When err != nil, n == 0.
  13. func (w *Writer) Write(b []byte) (int, error) {
  14. n := len(b)
  15. end := len(w.buf)
  16. if end+n > cap(w.buf) {
  17. buf := make([]byte, end, 2*cap(w.buf)+n)
  18. copy(buf, w.buf)
  19. w.buf = buf
  20. }
  21. w.buf = w.buf[:end+n]
  22. return copy(w.buf[end:], b), nil
  23. }
  24. // Len returns the length of the underlying byte slice.
  25. func (w *Writer) Len() int {
  26. return len(w.buf)
  27. }
  28. // Bytes returns the underlying byte slice.
  29. func (w *Writer) Bytes() []byte {
  30. return w.buf
  31. }
  32. // Reset empties and reuses the current buffer. Subsequent writes will overwrite the buffer, so any reference to the underlying slice is invalidated after this call.
  33. func (w *Writer) Reset() {
  34. w.buf = w.buf[:0]
  35. }