Debian Codegraph @

pkg/pool/pool.go

raw
1 package pool
2
3 import (
4 "strings"
5 "sync"
6 )
7
8 // Pooler is an interface that mimics a sync.Pool, but allows for different implementation.
9 type Pooler interface {
10 // Get returns a (newly allocated) byte slice.
11 Get() []byte
12 // Put returns the byte slice. This uses cap to determine the size of the buffer.
13 Put([]byte)
14 }
15
16 // Pool is the default pool used. The allocation size used is [server.UDPSize], if TCP allocations stay below
17 // this value too, it is also used for that, otherwise they escape and are garbage collected.
18 type Pool struct {
19 size int
20 pool sync.Pool
21 }
22
23 func (p *Pool) Get() []byte { return p.pool.Get().([]byte) }
24
25 func (p *Pool) Put(b []byte) {
26 if cap(b) > p.size {
27 return
28 }
29 p.pool.Put(b[:cap(b)])
30 }
31
32 // New returns a new Pooler of size.
33 func New(size int) *Pool {
34 return &Pool{
35 size: size,
36 pool: sync.Pool{
37 New: func() any { return make([]byte, size) },
38 },
39 }
40 }
41
42 // Noop is a Pooler that just allocates and does not cache.
43 type Noop struct {
44 size int
45 }
46
47 func (n *Noop) Get() []byte { return make([]byte, n.size) }
48 func (n *Noop) Put([]byte) {}
49
50 // NewNoop returns a new noop pool.
51 func NewNoop(size int) *Noop { return &Noop{size: size} }
52
53 // Builder is a pool used by the String methods.
54 type Builder struct {
55 sync.Pool
56 }
57
58 // NewBuilder returns a new builder pool.
59 func NewBuilder() *Builder {
60 return &Builder{New: func() any { return strings.Builder{} }}
61 }
62
63 func (s *Builder) Get() strings.Builder { return s.Pool.Get().(strings.Builder) }
64 func (s *Builder) Put(sb strings.Builder) { sb.Reset(); s.Pool.Put(sb) }