summaryrefslogtreecommitdiff
path: root/vendor/github.com/tdewolff/parse/v2/buffer/writer.go
blob: 6c94201ffb3ea9d0c6d221f6cfbf1e32aa7f3343 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package buffer

import (
	"io"
)

// Writer implements an io.Writer over a byte slice.
type Writer struct {
	buf    []byte
	err    error
	expand bool
}

// NewWriter returns a new Writer for a given byte slice.
func NewWriter(buf []byte) *Writer {
	return &Writer{
		buf:    buf,
		expand: true,
	}
}

// NewStaticWriter returns a new Writer for a given byte slice. It does not reallocate and expand the byte-slice.
func NewStaticWriter(buf []byte) *Writer {
	return &Writer{
		buf:    buf,
		expand: false,
	}
}

// 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.
func (w *Writer) Write(b []byte) (int, error) {
	n := len(b)
	end := len(w.buf)
	if end+n > cap(w.buf) {
		if !w.expand {
			w.err = io.EOF
			return 0, io.EOF
		}
		buf := make([]byte, end, 2*cap(w.buf)+n)
		copy(buf, w.buf)
		w.buf = buf
	}
	w.buf = w.buf[:end+n]
	return copy(w.buf[end:], b), nil
}

// Len returns the length of the underlying byte slice.
func (w *Writer) Len() int {
	return len(w.buf)
}

// Bytes returns the underlying byte slice.
func (w *Writer) Bytes() []byte {
	return w.buf
}

// 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.
func (w *Writer) Reset() {
	w.buf = w.buf[:0]
}

// Close returns the last error.
func (w *Writer) Close() error {
	return w.err
}