github.com/searKing/golang/go@v1.2.117/bufio/poolreader.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package bufio 6 7 import ( 8 "bufio" 9 "io" 10 "sync" 11 ) 12 13 type ReaderPool struct { 14 pool sync.Pool 15 size int 16 } 17 18 func NewReaderPool() *ReaderPool { 19 return &ReaderPool{} 20 } 21 22 func NewReaderPoolSize(size int) *ReaderPool { 23 return &ReaderPool{ 24 size: size, 25 } 26 } 27 28 func (p *ReaderPool) Put(br *bufio.Reader) { 29 br.Reset(nil) 30 p.pool.Put(br) 31 } 32 33 func (p *ReaderPool) Get(r io.Reader) *bufio.Reader { 34 if v := p.pool.Get(); v != nil { 35 br := v.(*bufio.Reader) 36 br.Reset(r) 37 return br 38 } 39 // Note: if this reader size is ever changed, update 40 // TestHandlerBodyClose's assumptions. 41 return bufio.NewReaderSize(r, p.size) 42 } 43 44 func (p *ReaderPool) Clear() { 45 // Get One elem in the pool 46 // for p.pool.New is nil, so p.pool.New will return nil if empty 47 if p.pool.Get() == nil { 48 // The pool is empty 49 return 50 } 51 p.Clear() 52 return 53 }