forked from multiformats/go-multihash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum.go
75 lines (62 loc) · 2.2 KB
/
sum.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
package multihash
import (
"fmt"
"hash"
"io"
mhreg "github.com/multiformats/go-multihash/core"
)
// ErrSumNotSupported is returned when the Sum function code is not implemented
var ErrSumNotSupported = mhreg.ErrSumNotSupported
var ErrLenTooLarge = mhreg.ErrLenTooLarge
// Sum obtains the cryptographic sum of a given buffer. The length parameter
// indicates the length of the resulting digest. Passing a negative value uses
// default length values for the selected hash function.
func Sum(data []byte, code uint64, length int) (Multihash, error) {
// Get the algorithm.
hasher, err := mhreg.GetVariableHasher(code, length)
if err != nil {
return nil, err
}
// Feed data in.
hasher.Write(data)
return encodeHash(hasher, code, length)
}
// SumStream obtains the cryptographic sum of a given stream. The length
// parameter indicates the length of the resulting digest. Passing a negative
// value uses default length values for the selected hash function.
func SumStream(r io.Reader, code uint64, length int) (Multihash, error) {
// Get the algorithm.
hasher, err := mhreg.GetVariableHasher(code, length)
if err != nil {
return nil, err
}
// Feed data in.
if _, err = io.Copy(hasher, r); err != nil {
return nil, err
}
return encodeHash(hasher, code, length)
}
func encodeHash(hasher hash.Hash, code uint64, length int) (Multihash, error) {
// Compute final hash.
// A new slice is allocated. FUTURE: see other comment below about allocation, and review together with this line to try to improve.
sum := hasher.Sum(nil)
// Deal with any truncation.
// Unless it's an identity multihash. Those have different rules.
if length < 0 {
length = hasher.Size()
}
if len(sum) < length {
return nil, ErrLenTooLarge
}
if length >= 0 {
if code == IDENTITY {
if length != len(sum) {
return nil, fmt.Errorf("the length of the identity hash (%d) must be equal to the length of the data (%d)", length, len(sum))
}
}
sum = sum[:length]
}
// Put the multihash metainfo bytes at the front of the buffer.
// FUTURE: try to improve allocations here. Encode does several which are probably avoidable, but it's the shape of the Encode method arguments that forces this.
return Encode(sum, code)
}