gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/pool/static-data-pool.go (about)

     1  package pool
     2  
     3  import (
     4  	"gitee.com/sy_183/go-common/assert"
     5  	"gitee.com/sy_183/go-common/log"
     6  	"gitee.com/sy_183/go-common/option"
     7  )
     8  
     9  var DebugLogger = assert.Must(log.Config{
    10  	Level: log.NewAtomicLevelAt(log.DebugLevel),
    11  	Encoder: log.NewConsoleEncoder(log.ConsoleEncoderConfig{
    12  		EncodeLevel: log.CapitalColorLevelEncoder,
    13  	}),
    14  }.Build())
    15  
    16  type StaticDataPool struct {
    17  	pool Pool[*Data]
    18  	size uint
    19  }
    20  
    21  func NewStaticDataPool(size uint, poolProvider PoolProvider[*Data], poolOptions ...option.AnyOption) *StaticDataPool {
    22  	return &StaticDataPool{
    23  		pool: poolProvider(func(p Pool[*Data]) *Data {
    24  			return newRefPoolData(p, size)
    25  		}, poolOptions...),
    26  		size: size,
    27  	}
    28  }
    29  
    30  func (p *StaticDataPool) Size() uint {
    31  	return p.size
    32  }
    33  
    34  func (p *StaticDataPool) Alloc(len uint) (d *Data) {
    35  	return p.AllocCap(len, len)
    36  }
    37  
    38  func (p *StaticDataPool) AllocCap(len, cap uint) (d *Data) {
    39  	if cap > p.size {
    40  		return nil
    41  	}
    42  	d = p.pool.Get()
    43  	if d == nil {
    44  		return nil
    45  	}
    46  	d.AddRef()
    47  	d.Data = d.raw[:len:cap]
    48  	return d
    49  }