@@ -3,6 +3,8 @@ package multihash
3
3
import (
4
4
"errors"
5
5
"fmt"
6
+ "hash"
7
+ "io"
6
8
7
9
mhreg "github.com/multiformats/go-multihash/core"
8
10
)
@@ -13,8 +15,8 @@ var ErrSumNotSupported = mhreg.ErrSumNotSupported
13
15
var ErrLenTooLarge = errors .New ("requested length was too large for digest" )
14
16
15
17
// Sum obtains the cryptographic sum of a given buffer. The length parameter
16
- // indicates the length of the resulting digest and passing a negative value
17
- // use default length values for the selected hash function.
18
+ // indicates the length of the resulting digest. Passing a negative value uses
19
+ // default length values for the selected hash function.
18
20
func Sum (data []byte , code uint64 , length int ) (Multihash , error ) {
19
21
// Get the algorithm.
20
22
hasher , err := GetHasher (code )
@@ -25,6 +27,28 @@ func Sum(data []byte, code uint64, length int) (Multihash, error) {
25
27
// Feed data in.
26
28
hasher .Write (data )
27
29
30
+ return encodeHash (hasher , code , length )
31
+ }
32
+
33
+ // SumStream obtains the cryptographic sum of a given stream. The length
34
+ // parameter indicates the length of the resulting digest. Passing a negative
35
+ // value uses default length values for the selected hash function.
36
+ func SumStream (r io.Reader , code uint64 , length int ) (Multihash , error ) {
37
+ // Get the algorithm.
38
+ hasher , err := GetHasher (code )
39
+ if err != nil {
40
+ return nil , err
41
+ }
42
+
43
+ // Feed data in.
44
+ if _ , err = io .Copy (hasher , r ); err != nil {
45
+ return nil , err
46
+ }
47
+
48
+ return encodeHash (hasher , code , length )
49
+ }
50
+
51
+ func encodeHash (hasher hash.Hash , code uint64 , length int ) (Multihash , error ) {
28
52
// Compute final hash.
29
53
// A new slice is allocated. FUTURE: see other comment below about allocation, and review together with this line to try to improve.
30
54
sum := hasher .Sum (nil )
0 commit comments