github.com/songzhibin97/gkit@v1.2.13/cache/buffer/iobuffer_pool.go (about)

     1  package buffer
     2  
     3  import "sync"
     4  
     5  // localIOPool
     6  var localIOPool IoPool
     7  
     8  // IoPool 存储 IoBuffer Pool
     9  type IoPool struct {
    10  	// IoBuffer
    11  	pool sync.Pool
    12  }
    13  
    14  // get 从pool中 获取一个 IoBuffer
    15  func (i *IoPool) get(size int) IoBuffer {
    16  	v := i.pool.Get()
    17  	if v == nil {
    18  		return newIoBuffer(size)
    19  	} else {
    20  		buf := v.(IoBuffer)
    21  		buf.Alloc(size)
    22  		buf.Count(1)
    23  		return buf
    24  	}
    25  }
    26  
    27  // put 向pool中回填一个 IoBuffer
    28  func (i *IoPool) put(buf IoBuffer) {
    29  	buf.Free()
    30  	i.pool.Put(buf)
    31  }
    32  
    33  // GetIoPool 从pool中 获取一个 IoBuffer
    34  func GetIoPool(size int) IoBuffer {
    35  	return localIOPool.get(size)
    36  }
    37  
    38  // PutIoPool 向pool中回填一个 IoBuffer
    39  func PutIoPool(buf IoBuffer) error {
    40  	count := buf.Count(-1)
    41  	if count > 0 {
    42  		// 还有其他引用
    43  		return nil
    44  	} else if count < 0 {
    45  		return ErrDuplicate
    46  	}
    47  	if p, _ := buf.(*pipe); p != nil {
    48  		buf = p.IoBuffer
    49  	}
    50  	localIOPool.put(buf)
    51  	return nil
    52  }
    53  
    54  // NewIoBuffer GetIoPool 别名
    55  func NewIoBuffer(size int) IoBuffer {
    56  	return GetIoPool(size)
    57  }