infra
/
goutils
Archived
1
0
Fork 0
This repository has been archived on 2022-04-06. You can view files and clone it, but cannot push or open issues or pull requests.
goutils/buf/bytebuf_pool.go

89 lines
1.8 KiB
Go

package buf
import (
"sync"
"unicode/utf8"
)
const (
defaultByteBufferSize = 4096
)
// ByteBuffer provides byte buffer, which can be used with fasthttp API
// in order to minimize memory allocations.
//
// ByteBuffer may be used with functions appending data to the given []byte
// slice. See example code for details.
//
// Use AcquireByteBuffer for obtaining an empty byte buffer.
type ByteBuffer struct {
// B is a byte buffer to use in append-like workloads.
// See example code for details.
B []byte
}
func (b *ByteBuffer) WriteByte(c byte) error {
b.B = append(b.B, c)
return nil
}
// Write implements io.Writer - it appends p to ByteBuffer.B
func (b *ByteBuffer) Write(p []byte) (int, error) {
b.B = append(b.B, p...)
return len(p), nil
}
// WriteString appends s to ByteBuffer.B
func (b *ByteBuffer) WriteString(s string) (int, error) {
b.B = append(b.B, s...)
return len(s), nil
}
//(r rune) (n int, err error) {
// WriteString appends s to ByteBuffer.B
func (b *ByteBuffer) WriteRune(r rune) (n int, err error) {
if r < utf8.RuneSelf {
b.B = append(b.B, byte(r))
return 1, nil
}
curSize := len(b.B)
runCharBuf := b.B[curSize:curSize+utf8.UTFMax]
n = utf8.EncodeRune(runCharBuf, r)
b.B = b.B[:curSize+n]
return n, nil
}
// Set sets ByteBuffer.B to p
func (b *ByteBuffer) Set(p []byte) {
b.B = append(b.B[:0], p...)
}
// SetString sets ByteBuffer.B to s
func (b *ByteBuffer) SetString(s string) {
b.B = append(b.B[:0], s...)
}
// Reset makes ByteBuffer.B empty.
func (b *ByteBuffer) Reset() {
b.B = b.B[:0]
}
type ByteBufferPool struct {
pool sync.Pool
}
func (p *ByteBufferPool) Acquire() *ByteBuffer {
v := p.pool.Get()
if v == nil {
return &ByteBuffer{
B: make([]byte, 0, defaultByteBufferSize),
}
}
return v.(*ByteBuffer)
}
func (p *ByteBufferPool) Release(b *ByteBuffer) {
b.Reset()
p.pool.Put(b)
}