gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

henc.go (989B)


      1 package pools
      2 
      3 import (
      4 	"hash"
      5 	"sync"
      6 
      7 	"codeberg.org/gruf/go-hashenc"
      8 )
      9 
     10 // HashEncoderPool is a pooled allocator for hashenc.HashEncoder objects.
     11 type HashEncoderPool interface {
     12 	// Get fetches a hashenc.HashEncoder from pool
     13 	Get() hashenc.HashEncoder
     14 
     15 	// Put places supplied hashenc.HashEncoder back in pool
     16 	Put(hashenc.HashEncoder)
     17 }
     18 
     19 // NewHashEncoderPool returns a newly instantiated hashenc.HashEncoder pool.
     20 func NewHashEncoderPool(hash func() hash.Hash, enc func() hashenc.Encoder) HashEncoderPool {
     21 	return &hencPool{
     22 		pool: sync.Pool{
     23 			New: func() interface{} {
     24 				return hashenc.New(hash(), enc())
     25 			},
     26 		},
     27 		size: hashenc.New(hash(), enc()).Size(),
     28 	}
     29 }
     30 
     31 // hencPool is our implementation of HashEncoderPool.
     32 type hencPool struct {
     33 	pool sync.Pool
     34 	size int
     35 }
     36 
     37 func (p *hencPool) Get() hashenc.HashEncoder {
     38 	return p.pool.Get().(hashenc.HashEncoder)
     39 }
     40 
     41 func (p *hencPool) Put(henc hashenc.HashEncoder) {
     42 	if henc.Size() < p.size {
     43 		return
     44 	}
     45 	p.pool.Put(henc)
     46 }