Files
smpp-tester/pdu/bufpool.go
PhatPhuckDave f30680c26f
Some checks failed
Benchmark BufferPool / RunBenchmarks (push) Failing after 17s
Run Tests / Test (push) Failing after 15s
Rework every uint8 to byte and rework every []byte to bytes.Buffer
I just learnt that uint8 and byte are the fucking same
And that bytes.Buffer is the thing to use
Idiot idiot idiot...
Live and learn
2024-07-24 18:48:12 +02:00

55 lines
979 B
Go

package pdu
import (
"bytes"
"sync"
)
type BufferPoolManager struct {
pools map[int]*sync.Pool
mu sync.RWMutex
}
func NewBufferPoolManager() *BufferPoolManager {
return &BufferPoolManager{
pools: make(map[int]*sync.Pool),
}
}
func (bpm *BufferPoolManager) Get(size int) *bytes.Buffer {
bpm.mu.RLock()
pool, exists := bpm.pools[size]
bpm.mu.RUnlock()
if !exists {
bpm.mu.Lock()
// Double-check if another goroutine added the pool while we were waiting
pool, exists = bpm.pools[size]
if !exists {
pool = &sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, size))
},
}
bpm.pools[size] = pool
}
bpm.mu.Unlock()
}
return pool.Get().(*bytes.Buffer);
}
func (bpm *BufferPoolManager) Put(buf *bytes.Buffer) {
size := buf.Len()
bpm.mu.RLock()
pool, exists := bpm.pools[size]
bpm.mu.RUnlock()
if !exists {
return
}
buf.Reset()
pool.Put(buf)
}