-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathbuffer.go
More file actions
424 lines (387 loc) · 13.9 KB
/
buffer.go
File metadata and controls
424 lines (387 loc) · 13.9 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bytes
// Simple byte buffer for marshaling data.
import (
"solod.dev/so/errors"
"solod.dev/so/io"
"solod.dev/so/math"
"solod.dev/so/mem"
"solod.dev/so/slices"
"solod.dev/so/unicode/utf8"
)
// ErrNegativeGrow means that a Buffer.Grow call was given a negative count.
var ErrNegativeGrow = errors.New("bytes: negative grow")
// MinRead is the minimum slice size passed to a [Buffer.Read] call by
// [Buffer.ReadFrom]. As long as the [Buffer] has at least MinRead bytes beyond
// what is required to hold the contents of r, [Buffer.ReadFrom] will not grow the
// underlying buffer.
const MinRead = 512
// smallBufferSize is an initial allocation minimal capacity.
const smallBufferSize = 64
// maxInt is the maximum value of an int.
const maxInt = int(math.MaxInt64)
// A Buffer is a variable-sized buffer of bytes with [Buffer.Read] and [Buffer.Write] methods.
// The zero value for Buffer is an empty buffer ready to use (with default allocator).
// A Buffer grows as needed when writing data, using the provided allocator.
// The caller is responsible for freeing the buffer's resources
// with [Buffer.Free] when done using it.
type Buffer struct {
a mem.Allocator // memory allocator; nil falls back to default one.
buf []byte // contents are the bytes buf[off : len(buf)]
off int // read at &buf[off], write at &buf[len(buf)]
}
// Bytes returns a slice of length b.Len() holding the unread portion of the buffer.
// The slice is valid for use only until the next buffer modification (that is,
// only until the next call to a method like [Buffer.Read], [Buffer.Write], [Buffer.Reset].
// The slice aliases the buffer content at least until the next buffer modification,
// so immediate changes to the slice will affect the result of future reads.
func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }
// String returns the contents of the unread portion of the buffer
// as a string. If the [Buffer] is a nil pointer, it returns "<nil>".
// The string is valid for use only until the next buffer modification.
//
// To build strings more efficiently, see the [strings.Builder] type.
func (b *Buffer) String() string {
if b == nil {
// Special case, useful in debugging.
return "<nil>"
}
return string(b.buf[b.off:])
}
// Peek returns the next n bytes without advancing the buffer.
// If Peek returns fewer than n bytes, it also returns [io.EOF].
// The slice is only valid until the next call to a read or write method.
// The slice aliases the buffer content at least until the next buffer modification,
// so immediate changes to the slice will affect the result of future reads.
func (b *Buffer) Peek(n int) ([]byte, error) {
if b.Len() < n {
return b.buf[b.off:], io.EOF
}
return b.buf[b.off : b.off+n], nil
}
// empty reports whether the unread portion of the buffer is empty.
func (b *Buffer) empty() bool { return len(b.buf) <= b.off }
// Len returns the number of bytes of the unread portion of the buffer;
// b.Len() == len(b.Bytes()).
func (b *Buffer) Len() int { return len(b.buf) - b.off }
// Cap returns the capacity of the buffer's underlying byte slice, that is, the
// total space allocated for the buffer's data.
func (b *Buffer) Cap() int { return cap(b.buf) }
// Available returns how many bytes are unused in the buffer.
func (b *Buffer) Available() int { return cap(b.buf) - len(b.buf) }
// Reset resets the buffer to be empty,
// but it retains the underlying storage for use by future writes.
func (b *Buffer) Reset() {
b.buf = b.buf[:0]
b.off = 0
}
// Free frees the internal buffer and resets the buffer.
// After Free, the buffer can be reused with new writes.
func (b *Buffer) Free() {
mem.FreeSlice(b.a, b.buf)
b.buf = nil
b.off = 0
}
// tryGrowByReslice is an inlineable version of grow for the fast-case where the
// internal buffer only needs to be resliced.
// It returns the index where bytes should be written and whether it succeeded.
func (b *Buffer) tryGrowByReslice(n int) (int, bool) {
if l := len(b.buf); n <= cap(b.buf)-l {
b.buf = b.buf[:l+n]
return l, true
}
return 0, false
}
// grow grows the buffer to guarantee space for n more bytes.
// It returns the index where bytes should be written.
// Panics if the buffer can't grow.
func (b *Buffer) grow(n int) int {
m := b.Len()
// If buffer is empty, reset to recover space.
if m == 0 && b.off != 0 {
b.Reset()
}
// Try to grow by means of a reslice.
if i, ok := b.tryGrowByReslice(n); ok {
return i
}
if b.buf == nil && n <= smallBufferSize {
b.buf = mem.AllocSlice[byte](b.a, n, smallBufferSize)
return 0
}
c := cap(b.buf)
if n <= c/2-m {
// We can slide things down instead of allocating a new
// slice. We only need m+n <= c to slide, but
// we instead let capacity get twice as large so we
// don't spend all our time copying.
copy(b.buf, b.buf[b.off:])
} else if c > maxInt-c-n {
panic("bytes: buffer overflow")
} else {
// Allocate a new buffer, copy live data, free the old one.
b.growBuf(m, n)
}
// Restore b.off and len(b.buf).
b.off = 0
b.buf = b.buf[:m+n]
return m
}
// growBuf allocates a new buffer with enough room for m+n bytes (where m is
// the live data length), copies the live portion (buf[off:]), and frees the
// old buffer.
func (b *Buffer) growBuf(m, n int) {
c := m + n // ensure enough space for n elements
c = max(c, 2*cap(b.buf)) // but double if it's less than double
buf := mem.AllocSlice[byte](b.a, c, c)
copy(buf, b.buf[b.off:])
mem.FreeSlice(b.a, b.buf)
b.buf = buf[:m]
}
// Grow grows the buffer's capacity, if necessary, to guarantee space for
// another n bytes. After Grow(n), at least n bytes can be written to the
// buffer without another allocation.
// Panics if n is negative or if the buffer cannot grow.
func (b *Buffer) Grow(n int) {
if n < 0 {
panic("bytes: negative grow")
}
m := b.grow(n)
b.buf = b.buf[:m]
}
// Write appends the contents of p to the buffer, growing the buffer as
// needed. The return value n is the length of p; err is always nil.
// Panics if the buffer becomes too large.
func (b *Buffer) Write(p []byte) (int, error) {
m, ok := b.tryGrowByReslice(len(p))
if !ok {
m = b.grow(len(p))
}
return copy(b.buf[m:], p), nil
}
// WriteString appends the contents of s to the buffer, growing the buffer as
// needed. The return value n is the length of s; err is always nil.
// Panics if the buffer becomes too large.
func (b *Buffer) WriteString(s string) (int, error) {
m, ok := b.tryGrowByReslice(len(s))
if !ok {
m = b.grow(len(s))
}
return copy(b.buf[m:], s), nil
}
// ReadFrom reads data from r until EOF and appends it to the buffer, growing
// the buffer as needed. The return value n is the number of bytes read. Any
// error except io.EOF encountered during the read is also returned.
// Panics if the buffer becomes too large.
func (b *Buffer) ReadFrom(r io.Reader) (int64, error) {
var n int64
for {
i := b.grow(MinRead)
b.buf = b.buf[:i]
m, err := r.Read(b.buf[i:cap(b.buf)])
if m < 0 {
return 0, io.ErrNegativeRead
}
b.buf = b.buf[:i+m]
n += int64(m)
if err == io.EOF {
return n, nil // err is EOF, so return nil explicitly
}
if err != nil {
return n, err
}
}
}
// WriteTo writes data to w until the buffer is drained or an error occurs.
// The return value n is the number of bytes written; it always fits into an
// int, but it is int64 to match the [io.WriterTo] interface. Any error
// encountered during the write is also returned.
func (b *Buffer) WriteTo(w io.Writer) (int64, error) {
var n int64
if nBytes := b.Len(); nBytes > 0 {
m, err := w.Write(b.buf[b.off:])
if m > nBytes {
return n, io.ErrInvalidWrite
}
b.off += m
n = int64(m)
if err != nil {
return n, err
}
// all bytes should have been written, by definition of
// Write method in io.Writer
if m != nBytes {
return n, io.ErrShortWrite
}
}
// Buffer is now empty; reset.
b.Reset()
return n, nil
}
// WriteByte appends the byte c to the buffer, growing the buffer as needed.
// The returned error is always nil, but is included to match [bufio.Writer]'s
// WriteByte. Panics if the buffer becomes too large.
func (b *Buffer) WriteByte(c byte) error {
m, ok := b.tryGrowByReslice(1)
if !ok {
m = b.grow(1)
}
b.buf[m] = c
return nil
}
// WriteRune appends the UTF-8 encoding of Unicode code point r to the
// buffer, returning its length and an error, which is always nil but is
// included to match [bufio.Writer]'s WriteRune. The buffer is grown as needed;
// if it becomes too large, WriteRune will panic.
func (b *Buffer) WriteRune(r rune) (int, error) {
// Compare as uint32 to correctly handle negative runes.
if uint32(r) < utf8.RuneSelf {
b.WriteByte(byte(r))
return 1, nil
}
m, ok := b.tryGrowByReslice(utf8.UTFMax)
if !ok {
m = b.grow(utf8.UTFMax)
}
b.buf = utf8.AppendRune(b.buf[:m], r)
return len(b.buf) - m, nil
}
// Read reads the next len(p) bytes from the buffer or until the buffer
// is drained. The return value n is the number of bytes read. If the
// buffer has no data to return, err is [io.EOF] (unless len(p) is zero);
// otherwise it is nil.
func (b *Buffer) Read(p []byte) (int, error) {
if b.empty() {
// Buffer is empty, reset to recover space.
b.Reset()
if len(p) == 0 {
return 0, nil
}
return 0, io.EOF
}
n := copy(p, b.buf[b.off:])
b.off += n
return n, nil
}
// Next returns a slice containing the next n bytes from the buffer,
// advancing the buffer as if the bytes had been returned by [Buffer.Read].
// If there are fewer than n bytes in the buffer, Next returns the entire buffer.
// The slice is only valid until the next call to a read or write method.
func (b *Buffer) Next(n int) []byte {
m := b.Len()
if n > m {
n = m
}
data := b.buf[b.off : b.off+n]
b.off += n
return data
}
// ReadByte reads and returns the next byte from the buffer.
// If no byte is available, it returns error [io.EOF].
func (b *Buffer) ReadByte() (byte, error) {
if b.empty() {
// Buffer is empty, reset to recover space.
b.Reset()
return 0, io.EOF
}
c := b.buf[b.off]
b.off++
return c, nil
}
// ReadRune reads and returns the next UTF-8-encoded
// Unicode code point from the buffer.
// If no bytes are available, the error returned is io.EOF.
// If the bytes are an erroneous UTF-8 encoding, it
// consumes one byte and returns U+FFFD, 1.
func (b *Buffer) ReadRune() io.RuneSizeResult {
if b.empty() {
// Buffer is empty, reset to recover space.
b.Reset()
return io.RuneSizeResult{Rune: 0, Size: 0, Err: io.EOF}
}
c := b.buf[b.off]
if c < utf8.RuneSelf {
b.off++
return io.RuneSizeResult{Rune: rune(c), Size: 1, Err: nil}
}
r, n := utf8.DecodeRune(b.buf[b.off:])
b.off += n
return io.RuneSizeResult{Rune: r, Size: n, Err: nil}
}
// ReadBytes reads until the first occurrence of delim in the input,
// returning a slice containing the data up to and including the delimiter.
// If ReadBytes encounters an error before finding a delimiter,
// it returns the data read before the error and the error itself (often [io.EOF]).
// ReadBytes returns err != nil if and only if the returned data does not end in
// delim.
//
// The returned slice is allocated; the caller owns it.
func (b *Buffer) ReadBytes(delim byte) ([]byte, error) {
slice, err := b.readSlice(delim)
// return a copy of slice. The buffer's backing array may
// be overwritten by later calls.
line := slices.Clone(b.a, slice)
return line, err
}
// readSlice is like ReadBytes but returns a reference to internal buffer data.
func (b *Buffer) readSlice(delim byte) ([]byte, error) {
var err error
i := IndexByte(b.buf[b.off:], delim)
end := b.off + i + 1
if i < 0 {
end = len(b.buf)
err = io.EOF
}
var line []byte
line = b.buf[b.off:end]
b.off = end
return line, err
}
// ReadString reads until the first occurrence of delim in the input,
// returning a string containing the data up to and including the delimiter.
// If ReadString encounters an error before finding a delimiter,
// it returns the data read before the error and the error itself (often [io.EOF]).
// ReadString returns err != nil if and only if the returned data does not end
// in delim.
//
// The returned string is allocated; the caller owns it.
func (b *Buffer) ReadString(delim byte) (string, error) {
slice, err := b.readSlice(delim)
return String(b.a, slice), err
}
// NewBuffer creates and initializes a new [Buffer] using buf as its
// initial contents. The new Buffer takes ownership of buf, and the
// caller should not use buf after this call. NewBuffer is intended to
// prepare a Buffer to read existing data. It can also be used to set
// the initial size of the internal buffer for writing. To do that,
// buf should have the desired capacity but a length of zero.
//
// If buf was allocated with an allocator, the same allocator must be
// passed to NewBuffer so that [Buffer.Free] can release it correctly.
// Do not call [Buffer.Free] if buf was not heap-allocated.
//
// Do not provide a stack-allocated buf if you intend to write to the buffer,
// as the buffer may need to grow and reallocate, which would cause free()
// on a stack pointer. Only use heap-allocated slices in this case.
//
// If the allocator is nil, uses the system allocator.
func NewBuffer(a mem.Allocator, buf []byte) Buffer {
return Buffer{a: a, buf: buf}
}
// NewBufferString creates and initializes a new [Buffer] using string s as its
// initial contents. It is intended to prepare a buffer to read an existing string.
//
// If s was allocated with an allocator, the same allocator must be
// passed to NewBuffer so that [Buffer.Free] can release it correctly.
// Do not call [Buffer.Free] if s was not heap-allocated.
//
// Do not provide a stack-allocated s if you intend to write to the buffer,
// as the buffer may need to grow and reallocate, which would cause free()
// on a stack pointer. Only use heap-allocated strings in this case.
//
// If the allocator is nil, uses the system allocator.
func NewBufferString(a mem.Allocator, s string) Buffer {
return Buffer{a: a, buf: []byte(s)}
}