-
Notifications
You must be signed in to change notification settings - Fork 0
/
buf.go
55 lines (48 loc) · 846 Bytes
/
buf.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
package main
import (
"sync"
)
type Buffer struct {
pool *sync.Pool
buf chan []byte
}
func NewBuffer() *Buffer {
b := &Buffer{
buf: make(chan []byte),
pool: &sync.Pool{
New: func() interface{} { return make([]byte, 1024) },
}}
return b
}
func (b *Buffer) Read(p []byte) (n int, err error) {
i := 0
buf := <-b.buf
i += copy(p[i:], buf)
b.returnReadBuffer(buf)
for i < len(p) {
select {
case buf := <-b.buf:
i += copy(p[i:], buf)
b.returnReadBuffer(buf)
default:
return i, nil
}
}
return i, nil
}
func (b *Buffer) returnReadBuffer(buf []byte) {
if cap(buf) > 256 {
b.pool.Put(buf)
}
}
func (b *Buffer) Write(data []byte) (int, error) {
i := 0
for i < len(data) {
buffer := b.pool.Get().([]byte)
l := copy(buffer, data[i:])
i += l
buffer = buffer[:l]
b.buf <- buffer
}
return i, nil
}