github.com/msales/pkg/v3@v3.24.0/bytes/buffer.go (about) 1 package bytes 2 3 import ( 4 "strconv" 5 "sync" 6 "time" 7 "unsafe" 8 ) 9 10 // Pool is a pool of Buffers. 11 type Pool struct { 12 p *sync.Pool 13 } 14 15 // NewPool creates a new instance of Pool. 16 func NewPool(size int) Pool { 17 return Pool{p: &sync.Pool{ 18 New: func() interface{} { 19 return &Buffer{b: make([]byte, 0, size)} 20 }, 21 }} 22 } 23 24 // Get retrieves a Buffer from the pool, creating one if necessary. 25 func (p Pool) Get() *Buffer { 26 buf := p.p.Get().(*Buffer) 27 buf.Reset() 28 return buf 29 } 30 31 // Put adds a Buffer to the pool. 32 func (p Pool) Put(buf *Buffer) { 33 p.p.Put(buf) 34 } 35 36 // Buffer wraps a byte slice, providing continence functions. 37 type Buffer struct { 38 b []byte 39 } 40 41 // AppendInt appends an integer to the underlying buffer. 42 func (b *Buffer) AppendInt(i int64) { 43 b.b = strconv.AppendInt(b.b, i, 10) 44 } 45 46 // AppendUint appends an unsigned integer to the underlying buffer. 47 func (b *Buffer) AppendUint(i uint64) { 48 b.b = strconv.AppendUint(b.b, i, 10) 49 } 50 51 // AppendFloat appends a float to the underlying buffer. 52 func (b *Buffer) AppendFloat(f float64, fmt byte, prec, bitSize int) { 53 b.b = strconv.AppendFloat(b.b, f, fmt, prec, bitSize) 54 } 55 56 // AppendBool appends a bool to the underlying buffer. 57 func (b *Buffer) AppendBool(v bool) { 58 b.b = strconv.AppendBool(b.b, v) 59 } 60 61 // AppendTime appends a time to the underlying buffer, in the given layout. 62 func (b *Buffer) AppendTime(t time.Time, layout string) { 63 b.b = t.AppendFormat(b.b, layout) 64 } 65 66 // WriteByte writes a single byte to the Buffer. 67 func (b *Buffer) WriteByte(v byte) error { 68 b.b = append(b.b, v) 69 return nil 70 } 71 72 // WriteString writes a string to the Buffer. 73 func (b *Buffer) WriteString(s string) { 74 b.b = append(b.b, s...) 75 } 76 77 // Write implements io.Writer. 78 func (b *Buffer) Write(bs []byte) (int, error) { 79 b.b = append(b.b, bs...) 80 81 return len(bs), nil 82 } 83 84 // Len returns the length of the underlying byte slice. 85 func (b *Buffer) Len() int { 86 return len(b.b) 87 } 88 89 // Cap returns the capacity of the underlying byte slice. 90 func (b *Buffer) Cap() int { 91 return cap(b.b) 92 } 93 94 // Bytes returns a mutable reference to the underlying byte slice. 95 func (b *Buffer) Bytes() []byte { 96 return b.b 97 } 98 99 // String returns a string of the underlying byte slice. 100 func (b *Buffer) String() string { 101 return *(*string)(unsafe.Pointer(&b.b)) 102 } 103 104 // Reset resets the underlying byte slice. Subsequent writes re-use the slice's 105 // backing array. 106 func (b *Buffer) Reset() { 107 b.b = b.b[:0] 108 }