Feat[pool]: add NewSizedBufferFactory

This commit is contained in:
kayos@tcp.direct 2023-01-18 16:13:44 -08:00
parent 25ae455041
commit 8d84965386
Signed by: kayos
GPG Key ID: 4B841471B4BEE979
2 changed files with 17 additions and 0 deletions

@ -18,6 +18,14 @@ func NewBufferFactory() BufferFactory {
}
}
func NewSizedBufferFactory(size int) BufferFactory {
return BufferFactory{
pool: &sync.Pool{
New: func() any { return bytes.NewBuffer(make([]byte, size)) },
},
}
}
func (cf BufferFactory) Put(buf *Buffer) error {
var err = ErrBufferReturned
buf.o.Do(func() {

@ -496,4 +496,13 @@ func TestBufferFactory(t *testing.T) {
t.Fatalf("The slice is not nil")
}
})
t.Run("NewSizedBufferFactory", func(t *testing.T) {
t.Parallel()
sized := NewSizedBufferFactory(4)
buf := sized.Get()
defer sized.MustPut(buf)
if buf.Cap() != 4 {
t.Errorf("Expected sized buffer from fresh factory to be cap == 4, got: %d", buf.Cap())
}
})
}