1
0
Fork 0
mirror of https://github.com/restic/restic.git synced 2024-12-23 08:16:36 +00:00
restic/internal/archiver/buffer.go

55 lines
1.1 KiB
Go
Raw Normal View History

2018-03-30 20:43:18 +00:00
package archiver
2024-08-27 09:26:52 +00:00
// buffer is a reusable buffer. After the buffer has been used, Release should
2018-03-30 20:43:18 +00:00
// be called so the underlying slice is put back into the pool.
2024-08-27 09:26:52 +00:00
type buffer struct {
2018-03-30 20:43:18 +00:00
Data []byte
2024-08-27 09:26:52 +00:00
pool *bufferPool
2018-03-30 20:43:18 +00:00
}
// Release puts the buffer back into the pool it came from.
2024-08-27 09:26:52 +00:00
func (b *buffer) Release() {
pool := b.pool
if pool == nil || cap(b.Data) > pool.defaultSize {
return
}
select {
case pool.ch <- b:
default:
2018-03-30 20:43:18 +00:00
}
}
2024-08-27 09:26:52 +00:00
// bufferPool implements a limited set of reusable buffers.
type bufferPool struct {
ch chan *buffer
2018-03-30 20:43:18 +00:00
defaultSize int
}
2024-08-27 09:26:52 +00:00
// newBufferPool initializes a new buffer pool. The pool stores at most max
// items. New buffers are created with defaultSize. Buffers that have grown
// larger are not put back.
2024-08-27 09:26:52 +00:00
func newBufferPool(max int, defaultSize int) *bufferPool {
b := &bufferPool{
ch: make(chan *buffer, max),
2018-03-30 20:43:18 +00:00
defaultSize: defaultSize,
}
return b
}
// Get returns a new buffer, either from the pool or newly allocated.
2024-08-27 09:26:52 +00:00
func (pool *bufferPool) Get() *buffer {
2018-03-30 20:43:18 +00:00
select {
case buf := <-pool.ch:
2018-04-29 13:34:41 +00:00
return buf
2018-03-30 20:43:18 +00:00
default:
2018-04-29 13:34:41 +00:00
}
2024-08-27 09:26:52 +00:00
b := &buffer{
2018-04-29 13:34:41 +00:00
Data: make([]byte, pool.defaultSize),
pool: pool,
2018-03-30 20:43:18 +00:00
}
return b
}