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