-
Notifications
You must be signed in to change notification settings - Fork 2
/
pools.go
102 lines (88 loc) · 1.59 KB
/
pools.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package emux
import (
"bufio"
"io"
"sync"
)
var (
readers = newReaderPool()
writers = newWriterPool()
limitReaders = newLimitReaderPool()
)
type readerPool struct {
pool sync.Pool
}
func newReaderPool() *readerPool {
return &readerPool{
pool: sync.Pool{
New: func() interface{} {
return bufio.NewReaderSize(nil, bufSize)
},
},
}
}
func (p *readerPool) Get(r io.Reader) io.Reader {
if _, ok := r.(ByteReader); ok {
return r
}
buf := p.pool.Get().(*bufio.Reader)
buf.Reset(r)
return buf
}
func (p *readerPool) Put(buf io.Reader) {
reader, ok := buf.(*bufio.Reader)
if ok {
reader.Reset(nil)
p.pool.Put(reader)
}
}
type limitReaderPool struct {
pool sync.Pool
}
func newLimitReaderPool() *limitReaderPool {
return &limitReaderPool{
pool: sync.Pool{
New: func() interface{} {
return &io.LimitedReader{}
},
},
}
}
func (p *limitReaderPool) Get(r io.Reader, n int64) *io.LimitedReader {
buf := p.pool.Get().(*io.LimitedReader)
buf.R = r
buf.N = n
return buf
}
func (p *limitReaderPool) Put(buf *io.LimitedReader) {
buf.N = 0
buf.R = nil
p.pool.Put(buf)
}
type writerPool struct {
pool sync.Pool
}
func newWriterPool() *writerPool {
return &writerPool{
pool: sync.Pool{
New: func() interface{} {
return bufio.NewWriterSize(nil, bufSize)
},
},
}
}
func (p *writerPool) Get(w io.Writer) io.Writer {
if _, ok := w.(Flusher); ok {
return w
}
buf := p.pool.Get().(*bufio.Writer)
buf.Reset(w)
return buf
}
func (p *writerPool) Put(w io.Writer) {
writer, ok := w.(*bufio.Writer)
if ok {
writer.Reset(nil)
p.pool.Put(writer)
}
}