writer.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package buffer
  2. import (
  3. "io"
  4. )
  5. // Writer implements an io.Writer over a byte slice.
  6. type Writer struct {
  7. buf []byte
  8. err error
  9. expand bool
  10. }
  11. // NewWriter returns a new Writer for a given byte slice.
  12. func NewWriter(buf []byte) *Writer {
  13. return &Writer{
  14. buf: buf,
  15. expand: true,
  16. }
  17. }
  18. // NewStaticWriter returns a new Writer for a given byte slice. It does not reallocate and expand the byte-slice.
  19. func NewStaticWriter(buf []byte) *Writer {
  20. return &Writer{
  21. buf: buf,
  22. expand: false,
  23. }
  24. }
  25. // 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.
  26. func (w *Writer) Write(b []byte) (int, error) {
  27. n := len(b)
  28. end := len(w.buf)
  29. if end+n > cap(w.buf) {
  30. if !w.expand {
  31. w.err = io.EOF
  32. return 0, io.EOF
  33. }
  34. buf := make([]byte, end, 2*cap(w.buf)+n)
  35. copy(buf, w.buf)
  36. w.buf = buf
  37. }
  38. w.buf = w.buf[:end+n]
  39. return copy(w.buf[end:], b), nil
  40. }
  41. // Len returns the length of the underlying byte slice.
  42. func (w *Writer) Len() int {
  43. return len(w.buf)
  44. }
  45. // Bytes returns the underlying byte slice.
  46. func (w *Writer) Bytes() []byte {
  47. return w.buf
  48. }
  49. // 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.
  50. func (w *Writer) Reset() {
  51. w.buf = w.buf[:0]
  52. }
  53. // Close returns the last error.
  54. func (w *Writer) Close() error {
  55. return w.err
  56. }