forked from djherbis/buffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
partition.go
101 lines (80 loc) · 1.51 KB
/
partition.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
package buffer
import (
"encoding/gob"
"io"
"math"
)
type partition struct {
List
Pool
}
// NewPartition returns a Buffer which uses a Pool to extend or shrink its size as needed.
// It automatically allocates new buffers with pool.Get() to extend is length, and
// pool.Put() to release unused buffers as it shrinks.
func NewPartition(pool Pool, buffers ...Buffer) Buffer {
return &partition{
Pool: pool,
List: buffers,
}
}
func (buf *partition) Cap() int64 {
return math.MaxInt64
}
func (buf *partition) Read(p []byte) (n int, err error) {
for len(p) > 0 {
if len(buf.List) == 0 {
return n, io.EOF
}
buffer := buf.List[0]
if Empty(buffer) {
buf.Pool.Put(buf.Pop())
continue
}
m, er := buffer.Read(p)
n += m
p = p[m:]
if er != nil && er != io.EOF {
return n, er
}
}
return n, nil
}
func (buf *partition) grow() error {
next, err := buf.Pool.Get()
if err != nil {
return err
}
buf.Push(next)
return nil
}
func (buf *partition) Write(p []byte) (n int, err error) {
for len(p) > 0 {
if len(buf.List) == 0 {
if err := buf.grow(); err != nil {
return n, err
}
}
buffer := buf.List[len(buf.List)-1]
if Full(buffer) {
if err := buf.grow(); err != nil {
return n, err
}
continue
}
m, er := buffer.Write(p)
n += m
p = p[m:]
if er != nil && er != io.ErrShortWrite {
return n, er
}
}
return n, nil
}
func (buf *partition) Reset() {
for len(buf.List) > 0 {
buf.Pool.Put(buf.Pop())
}
}
func init() {
gob.Register(&partition{})
}