-
Notifications
You must be signed in to change notification settings - Fork 15
/
multidim_byte_reader.go
51 lines (40 loc) · 1.21 KB
/
multidim_byte_reader.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
package helper
import (
"io"
)
type MultiDimByteReader struct {
s [][]byte // slices
currentSliceIndex int // index of current slice
currentIndexInCurrentSlice int // index of current byte in current slice
currentSliceLen int // length of current slice
totalLen int // total length of all slices
}
func (r *MultiDimByteReader) Read(b []byte) (n int, err error) {
if r.currentSliceIndex >= r.totalLen {
return 0, io.EOF
}
if r.currentIndexInCurrentSlice >= r.currentSliceLen {
return 0, io.EOF
}
n = copy(b, r.s[r.currentSliceIndex][r.currentIndexInCurrentSlice:])
if r.currentIndexInCurrentSlice+n >= r.currentSliceLen {
r.currentSliceIndex++
r.currentIndexInCurrentSlice = 0
r.currentSliceLen = getLen(r.s, r.currentSliceIndex)
} else {
r.currentIndexInCurrentSlice += n
}
return
}
func getLen(b [][]byte, index int) int {
if index >= len(b) {
return 0
}
return len(b[index])
}
func (r *MultiDimByteReader) Reset(b [][]byte) {
*r = MultiDimByteReader{b, 0, 0, getLen(b, 0), len(b)}
}
func NewMultiDimByteReader(b [][]byte) *MultiDimByteReader {
return &MultiDimByteReader{b, 0, 0, getLen(b, 0), len(b)}
}