github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/encoding/bufpool/bufpool.go (about)

     1  // Package bufpool is a freelist for bytes.Buffer objects.
     2  package bufpool
     3  
     4  import (
     5  	"bytes"
     6  	"sync"
     7  )
     8  
     9  var pool = &sync.Pool{New: func() interface{} { return bytes.NewBuffer(nil) }}
    10  
    11  // Get returns an initialized bytes.Buffer object.
    12  // It is like new(bytes.Buffer) except it uses the free list.
    13  // The caller should call Put when finished with the returned object.
    14  // Since Buffer.Bytes() returns the buffer's underlying slice,
    15  // it is not safe for that slice to escape the caller.
    16  // If the bytes need to escape, CopyBytes should be used.
    17  func Get() *bytes.Buffer {
    18  	return pool.Get().(*bytes.Buffer)
    19  }
    20  
    21  // Put resets the buffer and adds it to the freelist.
    22  func Put(b *bytes.Buffer) {
    23  	b.Reset()
    24  	pool.Put(b)
    25  }
    26  
    27  // CopyBytes returns a copy of the bytes contained in the buffer.
    28  // This slice is safe from updates in the underlying buffer,
    29  // allowing the buffer to be placed back in the free list.
    30  func CopyBytes(buf *bytes.Buffer) []byte {
    31  	b := buf.Bytes()
    32  	b2 := make([]byte, len(b))
    33  	copy(b2, b)
    34  	return b2
    35  }