-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader.go
More file actions
74 lines (67 loc) · 1.38 KB
/
Copy pathreader.go
File metadata and controls
74 lines (67 loc) · 1.38 KB
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
package compression
import (
"bytes"
"io"
"gnalloy.org/gnalloy/buffer"
)
func bytesReader(src []byte) io.Reader {
return bytes.NewReader(src)
}
func newByteBufReadSource(src buffer.ByteBuf) io.Reader {
if data, ok := buffer.ContiguousReadableBytes(src); ok {
return bytes.NewReader(data)
}
reader := &byteBufReadSource{}
reader.slices = src.ReadableSlices(reader.stack[:0])
return reader
}
func writeByteBufTo(dst io.Writer, src buffer.ByteBuf) error {
if src == nil || src.ReadableBytes() == 0 {
return nil
}
if data, ok := buffer.ContiguousReadableBytes(src); ok {
_, err := dst.Write(data)
return err
}
var stack [8][]byte
slices := src.ReadableSlices(stack[:0])
if len(slices) == 0 {
return buffer.ErrInvalidIndex
}
for _, part := range slices {
if len(part) == 0 {
continue
}
if _, err := dst.Write(part); err != nil {
return err
}
}
return nil
}
type byteBufReadSource struct {
stack [8][]byte
slices [][]byte
index int
offset int
}
func (r *byteBufReadSource) Read(dst []byte) (int, error) {
if len(dst) == 0 {
return 0, nil
}
written := 0
for written < len(dst) && r.index < len(r.slices) {
current := r.slices[r.index]
if r.offset >= len(current) {
r.index++
r.offset = 0
continue
}
n := copy(dst[written:], current[r.offset:])
written += n
r.offset += n
}
if written == 0 {
return 0, io.EOF
}
return written, nil
}