-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopy.go
72 lines (59 loc) · 1.27 KB
/
copy.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
package bp
import (
"bytes"
"errors"
"io"
)
const (
defaultCopyIOSize int = 16 * 1024
)
var (
ErrIOReadNagativeRead = errors.New("negative count from io.Read")
)
type CopyIOPool struct {
pool *BytePool
}
func (c *CopyIOPool) Copy(dst io.Writer, src io.Reader) (int64, error) {
buf := c.pool.Get()
defer c.pool.Put(buf)
return io.CopyBuffer(dst, src, buf)
}
func (c *CopyIOPool) ReadAll(src io.Reader) ([]byte, error) {
buf := c.pool.Get()
defer c.pool.Put(buf)
size := int64(0)
out := bytes.NewBuffer(make([]byte, 0, c.pool.bufSize))
for {
n, err := src.Read(buf)
if n < 0 {
return []byte{}, ErrIOReadNagativeRead
}
size += int64(n)
if err == io.EOF {
return out.Bytes(), nil
}
if err != nil {
return []byte{}, err
}
out.Write(buf[:n])
}
}
func (c *CopyIOPool) Len() int {
return c.pool.Len()
}
func (c *CopyIOPool) Cap() int {
return c.pool.Cap()
}
func NewCopyIOPool(poolSize int, bufSize int, funcs ...optionFunc) *CopyIOPool {
return &CopyIOPool{
pool: NewBytePool(poolSize, bufSize, funcs...),
}
}
func Copy(dst io.Writer, src io.Reader) (int64, error) {
c := NewCopyIOPool(1, defaultCopyIOSize)
return c.Copy(dst, src)
}
func ReadAll(src io.Reader) ([]byte, error) {
c := NewCopyIOPool(1, defaultCopyIOSize)
return c.ReadAll(src)
}