-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
79 lines (63 loc) · 1.35 KB
/
task.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
package mtd
import (
"context"
"io"
"net/http"
)
type Task struct {
URL string
// Threads uint
// ChunkSize int64
Chunks uint
BufSize int64
Client http.Client
Headers map[string]string
Dst io.WriterAt
Writer *Writer
Ctx context.Context
}
func (t Task) write(rc io.ReadCloser, bRange byteRange) (written int, err error) {
// Determine the smallest useable byte buffer size and allocate the space for it
bufSize := minInt64(t.BufSize, bRange.end-bRange.start+1)
buf := make([]byte, bufSize)
// Prepare backet for reusing
packet := packet{
buf: buf,
dst: t.Dst,
}
// Set offset for chunked downloads
if bRange.Valid() {
packet.off = bRange.start
}
for {
// Handle cancel without blocking
select {
case <-t.Ctx.Done():
return
default:
}
// Read up to bufSize bytes
var n int
n, err = io.ReadFull(rc, buf[:])
if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF {
return
}
// Break if no bytes were read (no bytes left to write)
if n == 0 {
break
}
// Set the packet's buffer as a slice of the newly read bytes
packet.buf = buf[:n]
// Write the packet
n, err = t.Writer.Write(packet)
// Update offset for next write
packet.off += int64(n)
// Update the total number of bytes written
written += n
// Handle any write errors
if err != nil {
return
}
}
return written, nil
}