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

     1  package pool
     2  
     3  type Buffer struct {
     4  	raw        []byte
     5  	dataPool   []Data
     6  	allocated  uint
     7  	reversed   uint
     8  	ref        AtomicRef
     9  	onReleased func(*Buffer)
    10  }
    11  
    12  func NewBuffer(size uint, reversed uint) *Buffer {
    13  	return &Buffer{
    14  		raw:      make([]byte, size),
    15  		reversed: reversed,
    16  	}
    17  }
    18  
    19  func (b *Buffer) SetOnReleased(onReleased func(*Buffer)) *Buffer {
    20  	b.onReleased = onReleased
    21  	return b
    22  }
    23  
    24  func (b *Buffer) Size() uint {
    25  	return uint(len(b.raw))
    26  }
    27  
    28  func (b *Buffer) Remain() uint {
    29  	return uint(len(b.raw)) - b.allocated
    30  }
    31  
    32  func (b *Buffer) Used() []byte {
    33  	return b.raw[:b.allocated]
    34  }
    35  
    36  func (b *Buffer) Unused() []byte {
    37  	return b.raw[b.allocated:]
    38  }
    39  
    40  func (b *Buffer) Get() []byte {
    41  	if b.Remain() < b.reversed {
    42  		return nil
    43  	}
    44  	return b.Unused()
    45  }
    46  
    47  func (b *Buffer) Alloc(size uint) *Data {
    48  	end := b.allocated + size
    49  	if end > uint(len(b.raw)) {
    50  		return nil
    51  	}
    52  	l := len(b.dataPool)
    53  	if l < cap(b.dataPool) {
    54  		b.dataPool = b.dataPool[:l+1]
    55  	} else {
    56  		b.dataPool = append(b.dataPool, Data{})
    57  	}
    58  	d := &b.dataPool[l]
    59  	d.Data = b.raw[b.allocated:end]
    60  	d.Reference = b
    61  	b.AddRef()
    62  	b.allocated += size
    63  	return d
    64  }
    65  
    66  func (b *Buffer) Release() bool {
    67  	if b.ref.Release() {
    68  		b.allocated = 0
    69  		b.dataPool = b.dataPool[:0]
    70  		if onReleased := b.onReleased; onReleased != nil {
    71  			onReleased(b)
    72  		}
    73  		return true
    74  	}
    75  	return false
    76  }
    77  
    78  func (b *Buffer) AddRef() {
    79  	b.ref.AddRef()
    80  }
    81  
    82  func (b *Buffer) Use() *Buffer {
    83  	b.AddRef()
    84  	return b
    85  }