From c558e54750cdb6ddbdcacf28246009e87cba4dfa Mon Sep 17 00:00:00 2001 From: PhatPhuckDave <> Date: Mon, 22 Jul 2024 22:58:09 +0200 Subject: [PATCH] Add a byte buffer pool --- pdu/bufpool.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 pdu/bufpool.go diff --git a/pdu/bufpool.go b/pdu/bufpool.go new file mode 100644 index 0000000..6ce6f74 --- /dev/null +++ b/pdu/bufpool.go @@ -0,0 +1,49 @@ +package pdu + +import ( + "sync" +) + +type BufferPoolManager struct { + pools map[int]*sync.Pool + mu sync.Mutex +} + +func NewBufferPoolManager() *BufferPoolManager { + return &BufferPoolManager{ + pools: make(map[int]*sync.Pool), + } +} + +func (bpm *BufferPoolManager) GetBuffer(size int) *([]uint8) { + bpm.mu.Lock() + pool, exists := bpm.pools[size] + if !exists { + pool = &sync.Pool{ + New: func() interface{} { + buf := make([]uint8, size) + return &buf + }, + } + bpm.pools[size] = pool + } + bpm.mu.Unlock() + return pool.Get().(*[]uint8) +} + +func (bpm *BufferPoolManager) PutBuffer(buf *([]uint8)) { + size := len(*buf) + bpm.mu.Lock() + pool, exists := bpm.pools[size] + if !exists { + bpm.mu.Unlock() + return + } + bpm.mu.Unlock() + + // Reset buffer (optional) + for i := range *buf { + (*buf)[i] = 0 + } + pool.Put(buf) +}