-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
57 lines (50 loc) · 1.03 KB
/
file.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
package concurrenthash
import (
"bufio"
"fmt"
"io"
"os"
)
// streamFile reads the file in blocks given a block size in ConcurrentHash and
// writes them to a given channel: blocks
func (c *ConcurrentHash) streamFile(filePath string, blocks chan<- block) error {
defer close(blocks)
var file, err = os.Open(filePath)
if err != nil {
return err
}
var r = bufio.NewReader(file)
var index int
for {
var data = make([]byte, c.BlockSize)
n, err := io.ReadFull(r, data)
data = data[:n]
if n == 0 {
if err == nil {
continue
}
if err == io.EOF {
break
}
var closeErr = file.Close()
if closeErr != nil {
return fmt.Errorf("close file err: %w, buf.Read err: %s", closeErr, err.Error()) // cant have two %w
}
return err
}
blocks <- block{Index: index, Data: data}
index++
if err != nil {
if err == io.EOF {
break
}
// assuming it is not an error
// if the last file block is short
if err == io.ErrUnexpectedEOF {
break
}
return err
}
}
return file.Close()
}