Debian Codegraph @

chop.go

raw
1 package desync
2
3 import (
4 "context"
5 "fmt"
6 "io"
7 "os"
8
9 "golang.org/x/sync/errgroup"
10 )
11
12 // ChopFile split a file according to a list of chunks obtained from an Index
13 // and stores them in the provided store
14 func ChopFile(ctx context.Context, name string, chunks []IndexChunk, ws WriteStore, n int, pb ProgressBar) error {
15 in := make(chan IndexChunk)
16 g, ctx := errgroup.WithContext(ctx)
17
18 // Setup and start the progressbar if any
19 pb.SetTotal(len(chunks))
20 pb.Start()
21 defer pb.Finish()
22
23 s := NewChunkStorage(ws)
24
25 // Start the workers, each having its own filehandle to read concurrently
26 for range n {
27 f, err := os.Open(name)
28 if err != nil {
29 return fmt.Errorf("unable to open file %s, %s", name, err)
30 }
31 defer f.Close()
32
33 g.Go(func() error {
34 for c := range in {
35 // Update progress bar if any
36 pb.Increment()
37
38 chunk, err := readChunkFromFile(f, c)
39 if err != nil {
40 return err
41 }
42
43 if err := s.StoreChunk(chunk); err != nil {
44 return err
45 }
46 }
47 return nil
48 })
49 }
50
51 // Feed the workers, stop if there are any errors
52 loop:
53 for _, c := range chunks {
54 select {
55 case <-ctx.Done():
56 break loop
57 case in <- c:
58 }
59 }
60
61 close(in)
62
63 return g.Wait()
64 }
65
66 // Helper function to read chunk contents from file
67 func readChunkFromFile(f *os.File, c IndexChunk) (*Chunk, error) {
68 var err error
69 b := make([]byte, c.Size)
70
71 // Position the filehandle to the place where the chunk is meant to come
72 // from within the file
73 if _, err = f.Seek(int64(c.Start), io.SeekStart); err != nil {
74 return nil, err
75 }
76 // Read the whole (uncompressed) chunk into memory
77 if _, err = io.ReadFull(f, b); err != nil {
78 return nil, err
79 }
80 return NewChunkWithID(c.ID, b, false)
81 }