File: pool.go

package info (click to toggle)
golang-github-bettercap-gatt 0.0~git20240808.ec4935e-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 568 kB
  • sloc: ansic: 82; asm: 18; makefile: 3
file content (43 lines) | stat: -rw-r--r-- 666 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package util

import "log"

type BytePool struct {
	pool  chan []byte
	width int
}

func NewBytePool(width int, depth int) *BytePool {
	return &BytePool{
		pool:  make(chan []byte, depth),
		width: width,
	}
}

func (p *BytePool) Close() {
	close(p.pool)
}

func (p *BytePool) Get() (b []byte) {
	select {
	case b = <-p.pool:
	default:
		b = make([]byte, p.width)
	}
	return b
}

func (p *BytePool) Put(b []byte) {
	// avoid panic: send on closed channel in case we're still processing
	// packets when the channel is closed
	defer func() {
		if err := recover(); err != nil {
			log.Printf("bytepool: %v", err)
		}
	}()

	select {
	case p.pool <- b:
	default:
	}
}