-
Notifications
You must be signed in to change notification settings - Fork 2
/
fileslice.go
63 lines (57 loc) · 1.04 KB
/
fileslice.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
package filehelper
import (
"io"
"os"
"golang.org/x/xerrors"
)
type FileSlice struct {
r *os.File
offset int64
start int64
end int64
fileSize int64
}
func NewFileSlice(r *os.File, offset, start, end, fileSize int64) *FileSlice {
return &FileSlice{
r: r,
offset: offset,
start: start,
end: end,
fileSize: fileSize,
}
}
func (fs *FileSlice) Read(p []byte) (n int, err error) {
if fs.end == 0 {
fs.end = fs.fileSize - 1
}
if fs.offset == 0 && fs.start > 0 {
_, err = fs.r.Seek(fs.start, 0)
if err != nil {
return 0, err
}
fs.offset = fs.start
}
if fs.end-fs.offset+1 == 0 {
return 0, io.EOF
}
if fs.end-fs.offset+1 < 0 {
return 0, xerrors.Errorf("read data out bound of the slice")
}
plen := len(p)
leftLen := fs.end - fs.offset + 1
if leftLen > int64(plen) {
n, err = fs.r.Read(p)
if err != nil {
return
}
fs.offset += int64(n)
return
}
b := make([]byte, leftLen)
n, err = fs.r.Read(b)
if err != nil {
return
}
fs.offset += int64(n)
return copy(p, b), io.EOF
}