-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathslicewriteseek.go
68 lines (61 loc) · 1.66 KB
/
slicewriteseek.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
package slicewriteseek
import "io"
// SliceWriteSeeker implements WriteSeeker on a slice
type SliceWriteSeeker struct {
Buffer []byte
Index int64
}
// New creates a new SliceWriteReader
func New() *SliceWriteSeeker {
return &SliceWriteSeeker{Buffer: []byte{}}
}
// Len returns the length of the underlying slice
func (sws *SliceWriteSeeker) Len() int64 {
return int64(len(sws.Buffer))
}
func (sws *SliceWriteSeeker) Read(p []byte) (n int, err error) {
toRead := sws.Index + int64(len(p))
switch {
case sws.Index == sws.Len():
p = []byte{}
case toRead <= sws.Len():
p = sws.Buffer[sws.Index : int(sws.Index)+len(p)]
case toRead > sws.Len():
p = sws.Buffer[sws.Index:]
}
n = len(p)
sws.Index += int64(len(p))
return
}
func (sws *SliceWriteSeeker) Write(p []byte) (n int, err error) {
writeLen := int64(len(p))
switch {
case sws.Len() == 0:
sws.Buffer = p
sws.Index = int64(len(p))
case sws.Index == sws.Len():
sws.Buffer = append(sws.Buffer, p...)
sws.Index += writeLen
case sws.Index < sws.Len():
switch {
case sws.Index+writeLen > sws.Len():
sws.Buffer = append(sws.Buffer[:sws.Index], p...)
case sws.Index+writeLen <= sws.Len():
sws.Buffer = append(sws.Buffer[:sws.Index], append(p, sws.Buffer[sws.Index+writeLen:]...)...)
}
sws.Index += writeLen
}
return len(p), err
}
// Seek sets the offset for the next Read or Write to offset, interpreted according to whence
func (sws *SliceWriteSeeker) Seek(offset int64, whence int) (int64, error) {
switch whence {
case io.SeekStart:
sws.Index = 0 + offset
case io.SeekCurrent:
sws.Index = sws.Index + offset
case io.SeekEnd:
sws.Index = sws.Len() + offset
}
return sws.Index, nil
}