|
| 1 | +package bytebufferpool |
| 2 | + |
| 3 | +// ByteBuffer provides byte buffer, which can be used for minimizing |
| 4 | +// memory allocations. |
| 5 | +// |
| 6 | +// ByteBuffer may be used with functions appending data to the given []byte |
| 7 | +// slice. See example code for details. |
| 8 | +// |
| 9 | +// Use AcquireByteBuffer for obtaining an empty byte buffer. |
| 10 | +type ByteBuffer struct { |
| 11 | + |
| 12 | + // B is a byte buffer to use in append-like workloads. |
| 13 | + // See example code for details. |
| 14 | + B []byte |
| 15 | +} |
| 16 | + |
| 17 | +// Write implements io.Writer - it appends p to ByteBuffer.B |
| 18 | +func (b *ByteBuffer) Write(p []byte) (int, error) { |
| 19 | + b.B = append(b.B, p...) |
| 20 | + return len(p), nil |
| 21 | +} |
| 22 | + |
| 23 | +// WriteString appends s to ByteBuffer.B |
| 24 | +func (b *ByteBuffer) WriteString(s string) (int, error) { |
| 25 | + b.B = append(b.B, s...) |
| 26 | + return len(s), nil |
| 27 | +} |
| 28 | + |
| 29 | +// Set sets ByteBuffer.B to p |
| 30 | +func (b *ByteBuffer) Set(p []byte) { |
| 31 | + b.B = append(b.B[:0], p...) |
| 32 | +} |
| 33 | + |
| 34 | +// SetString sets ByteBuffer.B to s |
| 35 | +func (b *ByteBuffer) SetString(s string) { |
| 36 | + b.B = append(b.B[:0], s...) |
| 37 | +} |
| 38 | + |
| 39 | +// Reset makes ByteBuffer.B empty. |
| 40 | +func (b *ByteBuffer) Reset() { |
| 41 | + b.B = b.B[:0] |
| 42 | +} |
| 43 | + |
| 44 | +// AcquireByteBuffer returns an empty byte buffer from the pool. |
| 45 | +// |
| 46 | +// Acquired byte buffer may be returned to the pool via ReleaseByteBuffer call. |
| 47 | +// This reduces the number of memory allocations required for byte buffer |
| 48 | +// management. |
| 49 | +func AcquireByteBuffer() *ByteBuffer { |
| 50 | + return defaultByteBufferPool.Acquire() |
| 51 | +} |
| 52 | + |
| 53 | +// ReleaseByteBuffer returns byte buffer to the pool. |
| 54 | +// |
| 55 | +// ByteBuffer.B mustn't be touched after returning it to the pool. |
| 56 | +// Otherwise data races will occur. |
| 57 | +func ReleaseByteBuffer(b *ByteBuffer) { |
| 58 | + defaultByteBufferPool.Release(b) |
| 59 | +} |
| 60 | + |
| 61 | +var defaultByteBufferPool byteBufferPool |
0 commit comments