forked from Angey40/BaiduPCS-Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.go
130 lines (111 loc) · 2.3 KB
/
block.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
package uploader
import (
"fmt"
"io"
"os"
"sync"
)
type (
// SplitUnit 将 io.ReaderAt 分割单元
SplitUnit interface {
Readed64
io.Seeker
Range() ReadRange
Left() int64
}
// ReadRange 读取io.ReaderAt范围
ReadRange struct {
Begin int64 `json:"begin"`
End int64 `json:"end"`
}
fileBlock struct {
readRange ReadRange
readed int64
readerAt io.ReaderAt
mu sync.Mutex
}
)
// SplitBlock 文件分块
func SplitBlock(fileSize, blockSize int64) (blockList []*BlockState) {
blocksNum := int(fileSize / blockSize)
if fileSize%blockSize != 0 {
blocksNum += 1
}
blockList = make([]*BlockState, 0, blocksNum)
var (
id int
begin, end int64
)
for i := 0; i < blocksNum-1; i++ {
end += blockSize
blockList = append(blockList, &BlockState{
ID: id,
Range: ReadRange{
Begin: begin,
End: end,
},
})
id++
begin = end
}
blockList = append(blockList, &BlockState{
ID: id,
Range: ReadRange{
Begin: begin,
End: fileSize,
},
})
return
}
// NewSplitUnit io.ReaderAt实现SplitUnit接口
func NewSplitUnit(readerAt io.ReaderAt, readRange ReadRange) SplitUnit {
return &fileBlock{
readerAt: readerAt,
readRange: readRange,
}
}
func (fb *fileBlock) Read(b []byte) (n int, err error) {
fb.mu.Lock()
defer fb.mu.Unlock()
if fb.readed+fb.readRange.Begin >= fb.readRange.End {
return 0, io.EOF
}
left := int(fb.Left())
if len(b) > left {
n, err = fb.readerAt.ReadAt(b[:left], fb.readed+fb.readRange.Begin)
} else {
n, err = fb.readerAt.ReadAt(b, fb.readed+fb.readRange.Begin)
}
fb.readed += int64(n)
return
}
func (fb *fileBlock) Seek(offset int64, whence int) (int64, error) {
fb.mu.Lock()
defer fb.mu.Unlock()
switch whence {
case os.SEEK_SET:
fb.readed = offset
case os.SEEK_CUR:
fb.readed += offset
case os.SEEK_END:
fb.readed = fb.readRange.End - fb.readRange.Begin + offset
default:
return 0, fmt.Errorf("unsupport whence: %d", whence)
}
if fb.readed < 0 {
fb.readed = 0
}
return fb.readed, nil
}
func (fb *fileBlock) Len() int64 {
return fb.readRange.End - fb.readRange.Begin
}
func (fb *fileBlock) Left() int64 {
return fb.readRange.End - fb.readRange.Begin - fb.readed
}
func (fb *fileBlock) Range() ReadRange {
return fb.readRange
}
func (fb *fileBlock) Readed() int64 {
return fb.readed
}