-
Notifications
You must be signed in to change notification settings - Fork 1
/
sha1file.go
53 lines (47 loc) · 1.05 KB
/
sha1file.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
package main
import (
"errors"
"io"
)
// Sha1File calculates SHA-1 of the file as it is read.
type Sha1File struct {
rs io.ReadSeeker
position int64
calculated int64
digest *sha1digest
}
func NewSha1File(rs io.ReadSeeker) *Sha1File {
return &Sha1File{
rs: rs,
digest: NewSha1(),
}
}
func (f *Sha1File) Read(p []byte) (int, error) {
if f.position > f.calculated {
return 0, errors.New("missing data for sha1")
}
prev := f.position
n, err := f.rs.Read(p)
f.position += int64(n)
if f.position > f.calculated {
crop := f.calculated - prev
c := p[crop:n]
f.digest.Write(c) // nolint: errcheck
f.calculated += int64(len(c))
}
return n, err
}
func (f *Sha1File) Seek(offset int64, whence int) (int64, error) {
newPosition, err := f.rs.Seek(offset, whence)
if err != nil {
return newPosition, err
}
if f.position < newPosition {
return newPosition, errors.New("seeking forward is not supported")
}
f.position = newPosition
return newPosition, nil
}
func (f *Sha1File) Sum(b []byte) []byte {
return f.digest.Sum(b)
}