-
Notifications
You must be signed in to change notification settings - Fork 44
/
chop.go
81 lines (67 loc) · 1.68 KB
/
chop.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
package desync
import (
"context"
"fmt"
"io"
"os"
"golang.org/x/sync/errgroup"
)
// ChopFile split a file according to a list of chunks obtained from an Index
// and stores them in the provided store
func ChopFile(ctx context.Context, name string, chunks []IndexChunk, ws WriteStore, n int, pb ProgressBar) error {
in := make(chan IndexChunk)
g, ctx := errgroup.WithContext(ctx)
// Setup and start the progressbar if any
pb.SetTotal(len(chunks))
pb.Start()
defer pb.Finish()
s := NewChunkStorage(ws)
// Start the workers, each having its own filehandle to read concurrently
for i := 0; i < n; i++ {
f, err := os.Open(name)
if err != nil {
return fmt.Errorf("unable to open file %s, %s", name, err)
}
defer f.Close()
g.Go(func() error {
for c := range in {
// Update progress bar if any
pb.Increment()
chunk, err := readChunkFromFile(f, c)
if err != nil {
return err
}
if err := s.StoreChunk(chunk); err != nil {
return err
}
}
return nil
})
}
// Feed the workers, stop if there are any errors
loop:
for _, c := range chunks {
select {
case <-ctx.Done():
break loop
case in <- c:
}
}
close(in)
return g.Wait()
}
// Helper function to read chunk contents from file
func readChunkFromFile(f *os.File, c IndexChunk) (*Chunk, error) {
var err error
b := make([]byte, c.Size)
// Position the filehandle to the place where the chunk is meant to come
// from within the file
if _, err = f.Seek(int64(c.Start), io.SeekStart); err != nil {
return nil, err
}
// Read the whole (uncompressed) chunk into memory
if _, err = io.ReadFull(f, b); err != nil {
return nil, err
}
return NewChunkWithID(c.ID, b, false)
}