-
Notifications
You must be signed in to change notification settings - Fork 3
/
hash.go
63 lines (54 loc) · 1021 Bytes
/
hash.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
package storage
import (
"hash"
"github.com/dennwc/cas/types"
)
func Hash() BlobWriter {
return &hashWriter{h: types.NewRef().Hash()}
}
type hashWriter struct {
h hash.Hash
size uint64
ref types.SizedRef
}
func (w *hashWriter) Size() uint64 {
return w.size
}
func (w *hashWriter) Write(p []byte) (int, error) {
if w.h == nil {
return 0, ErrBlobCompleted
}
n, err := w.h.Write(p)
w.size += uint64(n)
return n, err
}
func (w *hashWriter) Complete() (types.SizedRef, error) {
if w.h != nil {
w.ref.Ref = types.NewRef().WithHash(w.h)
w.ref.Size = w.size
w.h = nil
return w.ref, nil
}
if w.ref.Ref.Zero() {
return types.SizedRef{}, ErrBlobDiscarded
}
return w.ref, nil
}
func (w *hashWriter) Close() error {
if w.h == nil && !w.ref.Ref.Zero() {
return ErrBlobCompleted
}
w.h = nil
return nil
}
func (w *hashWriter) Commit() error {
if w.h != nil {
if _, err := w.Complete(); err != nil {
return err
}
}
if w.ref.Ref.Zero() {
return ErrBlobDiscarded
}
return nil
}