1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // This a copy of Go std bytes.Buffer with some modification
8 // and some features stripped.
15 // A Buffer is a variable-sized buffer of bytes with Read and Write methods.
16 // The zero value for Buffer is an empty buffer ready to use.
18 buf []byte // contents are the bytes buf[off : len(buf)]
19 off int // read at &buf[off], write at &buf[len(buf)]
20 bootstrap [64]byte // memory to hold first slice; helps small buffers (Printf) avoid allocation.
23 // Bytes returns a slice of the contents of the unread portion of the buffer;
24 // len(b.Bytes()) == b.Len(). If the caller changes the contents of the
25 // returned slice, the contents of the buffer will change provided there
26 // are no intervening method calls on the Buffer.
27 func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }
29 // String returns the contents of the unread portion of the buffer
30 // as a string. If the Buffer is a nil pointer, it returns "<nil>".
31 func (b *Buffer) String() string {
33 // Special case, useful in debugging.
36 return string(b.buf[b.off:])
39 // Len returns the number of bytes of the unread portion of the buffer;
40 // b.Len() == len(b.Bytes()).
41 func (b *Buffer) Len() int { return len(b.buf) - b.off }
43 // Truncate discards all but the first n unread bytes from the buffer.
44 // It panics if n is negative or greater than the length of the buffer.
45 func (b *Buffer) Truncate(n int) {
47 case n < 0 || n > b.Len():
48 panic("leveldb/util.Buffer: truncation out of range")
50 // Reuse buffer space.
53 b.buf = b.buf[0 : b.off+n]
56 // Reset resets the buffer so it has no content.
57 // b.Reset() is the same as b.Truncate(0).
58 func (b *Buffer) Reset() { b.Truncate(0) }
60 // grow grows the buffer to guarantee space for n more bytes.
61 // It returns the index where bytes should be written.
62 // If the buffer can't grow it will panic with bytes.ErrTooLarge.
63 func (b *Buffer) grow(n int) int {
65 // If buffer is empty, reset to recover space.
66 if m == 0 && b.off != 0 {
69 if len(b.buf)+n > cap(b.buf) {
71 if b.buf == nil && n <= len(b.bootstrap) {
73 } else if m+n <= cap(b.buf)/2 {
74 // We can slide things down instead of allocating a new
75 // slice. We only need m+n <= cap(b.buf) to slide, but
76 // we instead let capacity get twice as large so we
77 // don't spend all our time copying.
78 copy(b.buf[:], b.buf[b.off:])
81 // not enough space anywhere
82 buf = makeSlice(2*cap(b.buf) + n)
83 copy(buf, b.buf[b.off:])
88 b.buf = b.buf[0 : b.off+m+n]
92 // Alloc allocs n bytes of slice from the buffer, growing the buffer as
93 // needed. If n is negative, Alloc will panic.
94 // If the buffer can't grow it will panic with bytes.ErrTooLarge.
95 func (b *Buffer) Alloc(n int) []byte {
97 panic("leveldb/util.Buffer.Alloc: negative count")
103 // Grow grows the buffer's capacity, if necessary, to guarantee space for
104 // another n bytes. After Grow(n), at least n bytes can be written to the
105 // buffer without another allocation.
106 // If n is negative, Grow will panic.
107 // If the buffer can't grow it will panic with bytes.ErrTooLarge.
108 func (b *Buffer) Grow(n int) {
110 panic("leveldb/util.Buffer.Grow: negative count")
116 // Write appends the contents of p to the buffer, growing the buffer as
117 // needed. The return value n is the length of p; err is always nil. If the
118 // buffer becomes too large, Write will panic with bytes.ErrTooLarge.
119 func (b *Buffer) Write(p []byte) (n int, err error) {
121 return copy(b.buf[m:], p), nil
124 // MinRead is the minimum slice size passed to a Read call by
125 // Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond
126 // what is required to hold the contents of r, ReadFrom will not grow the
127 // underlying buffer.
130 // ReadFrom reads data from r until EOF and appends it to the buffer, growing
131 // the buffer as needed. The return value n is the number of bytes read. Any
132 // error except io.EOF encountered during the read is also returned. If the
133 // buffer becomes too large, ReadFrom will panic with bytes.ErrTooLarge.
134 func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {
135 // If buffer is empty, reset to recover space.
136 if b.off >= len(b.buf) {
140 if free := cap(b.buf) - len(b.buf); free < MinRead {
141 // not enough space at end
143 if b.off+free < MinRead {
144 // not enough space using beginning of buffer;
145 // double buffer capacity
146 newBuf = makeSlice(2*cap(b.buf) + MinRead)
148 copy(newBuf, b.buf[b.off:])
149 b.buf = newBuf[:len(b.buf)-b.off]
152 m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])
153 b.buf = b.buf[0 : len(b.buf)+m]
162 return n, nil // err is EOF, so return nil explicitly
165 // makeSlice allocates a slice of size n. If the allocation fails, it panics
166 // with bytes.ErrTooLarge.
167 func makeSlice(n int) []byte {
168 // If the make fails, give a known error.
170 if recover() != nil {
171 panic(bytes.ErrTooLarge)
174 return make([]byte, n)
177 // WriteTo writes data to w until the buffer is drained or an error occurs.
178 // The return value n is the number of bytes written; it always fits into an
179 // int, but it is int64 to match the io.WriterTo interface. Any error
180 // encountered during the write is also returned.
181 func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) {
182 if b.off < len(b.buf) {
184 m, e := w.Write(b.buf[b.off:])
186 panic("leveldb/util.Buffer.WriteTo: invalid Write count")
193 // all bytes should have been written, by definition of
194 // Write method in io.Writer
196 return n, io.ErrShortWrite
199 // Buffer is now empty; reset.
204 // WriteByte appends the byte c to the buffer, growing the buffer as needed.
205 // The returned error is always nil, but is included to match bufio.Writer's
206 // WriteByte. If the buffer becomes too large, WriteByte will panic with
207 // bytes.ErrTooLarge.
208 func (b *Buffer) WriteByte(c byte) error {
214 // Read reads the next len(p) bytes from the buffer or until the buffer
215 // is drained. The return value n is the number of bytes read. If the
216 // buffer has no data to return, err is io.EOF (unless len(p) is zero);
217 // otherwise it is nil.
218 func (b *Buffer) Read(p []byte) (n int, err error) {
219 if b.off >= len(b.buf) {
220 // Buffer is empty, reset to recover space.
227 n = copy(p, b.buf[b.off:])
232 // Next returns a slice containing the next n bytes from the buffer,
233 // advancing the buffer as if the bytes had been returned by Read.
234 // If there are fewer than n bytes in the buffer, Next returns the entire buffer.
235 // The slice is only valid until the next call to a read or write method.
236 func (b *Buffer) Next(n int) []byte {
241 data := b.buf[b.off : b.off+n]
246 // ReadByte reads and returns the next byte from the buffer.
247 // If no byte is available, it returns error io.EOF.
248 func (b *Buffer) ReadByte() (c byte, err error) {
249 if b.off >= len(b.buf) {
250 // Buffer is empty, reset to recover space.
259 // ReadBytes reads until the first occurrence of delim in the input,
260 // returning a slice containing the data up to and including the delimiter.
261 // If ReadBytes encounters an error before finding a delimiter,
262 // it returns the data read before the error and the error itself (often io.EOF).
263 // ReadBytes returns err != nil if and only if the returned data does not end in
265 func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {
266 slice, err := b.readSlice(delim)
267 // return a copy of slice. The buffer's backing array may
268 // be overwritten by later calls.
269 line = append(line, slice...)
273 // readSlice is like ReadBytes but returns a reference to internal buffer data.
274 func (b *Buffer) readSlice(delim byte) (line []byte, err error) {
275 i := bytes.IndexByte(b.buf[b.off:], delim)
281 line = b.buf[b.off:end]
286 // NewBuffer creates and initializes a new Buffer using buf as its initial
287 // contents. It is intended to prepare a Buffer to read existing data. It
288 // can also be used to size the internal buffer for writing. To do that,
289 // buf should have the desired capacity but a length of zero.
291 // In most cases, new(Buffer) (or just declaring a Buffer variable) is
292 // sufficient to initialize a Buffer.
293 func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }