diff --git a/pool.go b/pool.go index e483a4ed8a813c142e2b6d2f02bd7bcc1a440129..d812840aaa96cd3ed49a4be37214123ff196347c 100644 --- a/pool.go +++ b/pool.go @@ -41,6 +41,11 @@ const MaxLength = math.MaxInt32 // You MUST NOT copy Pool after using. type BufferPool struct { pools [32]sync.Pool // a list of singlePools + ptrs sync.Pool +} + +type bufp struct { + buf []byte } // Get retrieves a buffer of the appropriate length from the buffer pool or @@ -57,8 +62,12 @@ func (p *BufferPool) Get(length int) []byte { return make([]byte, length) } idx := nextLogBase2(uint32(length)) - if buf := p.pools[idx].Get(); buf != nil { - return buf.([]byte)[:uint32(length)] + if ptr := p.pools[idx].Get(); ptr != nil { + bp := ptr.(*bufp) + buf := bp.buf[:uint32(length)] + bp.buf = nil + p.ptrs.Put(ptr) + return buf } return make([]byte, 1< 100 { + t.Fatalf("expected less than 100 frees after GC, got %d", frees) + } +} + func TestPool(t *testing.T) { // disable GC so we can control when it happens. defer debug.SetGCPercent(debug.SetGCPercent(-1))