| 1 | package render |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | ) |
| 6 | |
| 7 | // Pulled from the github.com/oxtoacart/bpool package (Apache licensed). |
| 8 | |
| 9 | // SizedBufferPool implements a pool of bytes.Buffers in the form of a bounded |
| 10 | // channel. Buffers are pre-allocated to the requested size. |
| 11 | type SizedBufferPool struct { |
| 12 | c chan *bytes.Buffer |
| 13 | a int |
| 14 | } |
| 15 | |
| 16 | // NewSizedBufferPool creates a new BufferPool bounded to the given size. |
| 17 | // size defines the number of buffers to be retained in the pool and alloc sets |
| 18 | // the initial capacity of new buffers to minimize calls to make(). |
| 19 | // |
| 20 | // The value of alloc should seek to provide a buffer that is representative of |
| 21 | // most data written to the the buffer (i.e. 95th percentile) without being |
| 22 | // overly large (which will increase static memory consumption). You may wish to |
| 23 | // track the capacity of your last N buffers (i.e. using an []int) prior to |
| 24 | // returning them to the pool as input into calculating a suitable alloc value. |
| 25 | func NewSizedBufferPool(size int, alloc int) (bp *SizedBufferPool) { |
| 26 | return &SizedBufferPool{ |
| 27 | c: make(chan *bytes.Buffer, size), |
| 28 | a: alloc, |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | // Get gets a Buffer from the SizedBufferPool, or creates a new one if none are |
| 33 | // available in the pool. Buffers have a pre-allocated capacity. |
| 34 | func (bp *SizedBufferPool) Get() (b *bytes.Buffer) { |
| 35 | select { |
| 36 | case b = <-bp.c: |
| 37 | // reuse existing buffer |
| 38 | default: |
| 39 | // create new buffer |
| 40 | b = bytes.NewBuffer(make([]byte, 0, bp.a)) |
| 41 | } |
| 42 | return |
| 43 | } |
| 44 | |
| 45 | // Put returns the given Buffer to the SizedBufferPool. |
| 46 | func (bp *SizedBufferPool) Put(b *bytes.Buffer) { |
| 47 | b.Reset() |
| 48 | |
| 49 | // Release buffers over our maximum capacity and re-create a pre-sized |
| 50 | // buffer to replace it. |
| 51 | // Note that the cap(b.Bytes()) provides the capacity from the read off-set |
| 52 | // only, but as we've called b.Reset() the full capacity of the underlying |
| 53 | // byte slice is returned. |
| 54 | if cap(b.Bytes()) > bp.a { |
| 55 | b = bytes.NewBuffer(make([]byte, 0, bp.a)) |
| 56 | } |
| 57 | |
| 58 | select { |
| 59 | case bp.c <- b: |
| 60 | default: // Discard the buffer if the pool is full. |
| 61 | } |
| 62 | } |