-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer.go
153 lines (113 loc) · 2.37 KB
/
buffer.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package seekbuffer
import (
"errors"
"fmt"
"io"
)
// SeekBuffer like bytes.Buffer but with Seek. NOT THREAD SAFE!!!
type SeekBuffer struct {
buff []byte
readPos int64
writePos int64
closed bool
rewindWhenFullReaded bool
}
func (b *SeekBuffer) WithAutoRewind() {
b.rewindWhenFullReaded = true
}
func (b *SeekBuffer) grow(n int) {
if cap(b.buff) > len(b.buff)+n {
return
}
newBuff := make([]byte, int(b.writePos)+n, int(b.writePos)+n)
copy(newBuff, b.buff)
b.buff = newBuff
}
func (b *SeekBuffer) Bytes() []byte {
return b.buff[:b.writePos]
}
func (b *SeekBuffer) Reset() {
if b.closed {
return
}
b.buff = nil
b.writePos = 0
b.readPos = 0
}
func (b *SeekBuffer) Len() int {
if b.closed {
return 0
}
return int(b.writePos)
}
func (b *SeekBuffer) Read(p []byte) (n int, err error) {
if b.closed {
return 0, fmt.Errorf("buffer is closed")
}
n = copy(p, b.buff[b.readPos:])
b.readPos += int64(n)
if b.readPos == b.writePos {
if b.rewindWhenFullReaded {
b.Seek(0, io.SeekStart)
}
return n, io.EOF
}
return n, nil
}
func (b *SeekBuffer) Close() error {
b.buff = nil
b.readPos = 0
b.writePos = 0
b.closed = true
return nil
}
func (b *SeekBuffer) Seek(offset int64, whence int) (int64, error) {
if b.closed {
return 0, fmt.Errorf("buffer is closed")
}
newPos := b.readPos //nolint
switch whence {
case io.SeekStart:
newPos = offset
case io.SeekCurrent:
newPos = b.readPos + offset
case io.SeekEnd:
newPos = b.writePos - offset
default:
return 0, errors.New("invalid whence value")
}
if newPos < 0 || newPos > b.writePos {
return 0, errors.New("seek position out of range")
}
b.readPos = newPos
return b.readPos, nil
}
func (b *SeekBuffer) Write(p []byte) (n int, err error) {
if b.closed {
return 0, fmt.Errorf("buffer is closed")
}
if len(b.buff) == 0 {
tmp := make([]byte, len(p), cap(p))
copy(tmp, p)
b.buff = tmp
b.writePos = int64(len(p))
return len(p), nil
}
b.grow(len(p))
copy(b.buff[b.writePos:], p)
b.writePos += int64(len(p))
return len(p), nil
}
/*
Replace replaces the content of the SeekBuffer
*/
func (b *SeekBuffer) Replace(p []byte) {
if len(p) > len(b.buff) {
b.grow(len(p) - int(b.writePos))
} else if len(p) < len(b.buff) {
b.buff = b.buff[:len(p)]
}
copy(b.buff, p)
b.writePos = int64(len(p))
b.readPos = 0
}