bufio.go (1863B)
1 package pools 2 3 import ( 4 "bufio" 5 "io" 6 "sync" 7 ) 8 9 // BufioReaderPool is a pooled allocator for bufio.Reader objects. 10 type BufioReaderPool interface { 11 // Get fetches a bufio.Reader from pool and resets to supplied reader 12 Get(io.Reader) *bufio.Reader 13 14 // Put places supplied bufio.Reader back in pool 15 Put(*bufio.Reader) 16 } 17 18 // NewBufioReaderPool returns a newly instantiated bufio.Reader pool. 19 func NewBufioReaderPool(size int) BufioReaderPool { 20 return &bufioReaderPool{ 21 pool: sync.Pool{ 22 New: func() interface{} { 23 return bufio.NewReaderSize(nil, size) 24 }, 25 }, 26 size: size, 27 } 28 } 29 30 // bufioReaderPool is our implementation of BufioReaderPool. 31 type bufioReaderPool struct { 32 pool sync.Pool 33 size int 34 } 35 36 func (p *bufioReaderPool) Get(r io.Reader) *bufio.Reader { 37 br := p.pool.Get().(*bufio.Reader) 38 br.Reset(r) 39 return br 40 } 41 42 func (p *bufioReaderPool) Put(br *bufio.Reader) { 43 if br.Size() < p.size { 44 return 45 } 46 br.Reset(nil) 47 p.pool.Put(br) 48 } 49 50 // BufioWriterPool is a pooled allocator for bufio.Writer objects. 51 type BufioWriterPool interface { 52 // Get fetches a bufio.Writer from pool and resets to supplied writer 53 Get(io.Writer) *bufio.Writer 54 55 // Put places supplied bufio.Writer back in pool 56 Put(*bufio.Writer) 57 } 58 59 // NewBufioWriterPool returns a newly instantiated bufio.Writer pool. 60 func NewBufioWriterPool(size int) BufioWriterPool { 61 return &bufioWriterPool{ 62 pool: sync.Pool{ 63 New: func() interface{} { 64 return bufio.NewWriterSize(nil, size) 65 }, 66 }, 67 size: size, 68 } 69 } 70 71 // bufioWriterPool is our implementation of BufioWriterPool. 72 type bufioWriterPool struct { 73 pool sync.Pool 74 size int 75 } 76 77 func (p *bufioWriterPool) Get(w io.Writer) *bufio.Writer { 78 bw := p.pool.Get().(*bufio.Writer) 79 bw.Reset(w) 80 return bw 81 } 82 83 func (p *bufioWriterPool) Put(bw *bufio.Writer) { 84 if bw.Size() < p.size { 85 return 86 } 87 bw.Reset(nil) 88 p.pool.Put(bw) 89 }