github.com/searKing/golang/go@v1.2.117/bufio/poolwriter.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 WriterPool struct { 14 pool sync.Pool 15 size int 16 } 17 18 func NewWriterPool() *WriterPool { 19 return &WriterPool{} 20 } 21 22 func NewWriterPoolSize(size int) *WriterPool { 23 return &WriterPool{ 24 size: size, 25 } 26 } 27 28 func (p *WriterPool) Put(br *bufio.Writer) { 29 br.Reset(nil) 30 p.pool.Put(br) 31 } 32 33 func (p *WriterPool) Get(w io.Writer) *bufio.Writer { 34 if v := p.pool.Get(); v != nil { 35 bw := v.(*bufio.Writer) 36 bw.Reset(w) 37 return bw 38 } 39 // Note: if this reader size is ever changed, update 40 // TestHandlerBodyClose's assumptions. 41 return bufio.NewWriterSize(w, p.size) 42 } 43 44 func (p *WriterPool) 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 }