summaryrefslogtreecommitdiff
path: root/vendor/codeberg.org/gruf/go-pools/henc.go
blob: cad905af429c923f78035c79704a50898d38b6f8 (plain)
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
44
45
46
package pools

import (
	"hash"
	"sync"

	"codeberg.org/gruf/go-hashenc"
)

// HashEncoderPool is a pooled allocator for hashenc.HashEncoder objects.
type HashEncoderPool interface {
	// Get fetches a hashenc.HashEncoder from pool
	Get() hashenc.HashEncoder

	// Put places supplied hashenc.HashEncoder back in pool
	Put(hashenc.HashEncoder)
}

// NewHashEncoderPool returns a newly instantiated hashenc.HashEncoder pool.
func NewHashEncoderPool(hash func() hash.Hash, enc func() hashenc.Encoder) HashEncoderPool {
	return &hencPool{
		pool: sync.Pool{
			New: func() interface{} {
				return hashenc.New(hash(), enc())
			},
		},
		size: hashenc.New(hash(), enc()).Size(),
	}
}

// hencPool is our implementation of HashEncoderPool.
type hencPool struct {
	pool sync.Pool
	size int
}

func (p *hencPool) Get() hashenc.HashEncoder {
	return p.pool.Get().(hashenc.HashEncoder)
}

func (p *hencPool) Put(henc hashenc.HashEncoder) {
	if henc.Size() < p.size {
		return
	}
	p.pool.Put(henc)
}