Skip to content

Commit 75ae368

Browse files
authored
Merge pull request #138 from gammazero/read-from-stream
New SumStream function reads from io.Reader
2 parents c3ba253 + 707d9c2 commit 75ae368

File tree

2 files changed

+27
-9
lines changed

2 files changed

+27
-9
lines changed

opts/opts.go

+1-7
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import (
88
"flag"
99
"fmt"
1010
"io"
11-
"io/ioutil"
1211
"sort"
1312
"strings"
1413

@@ -149,10 +148,5 @@ func (o *Options) Check(r io.Reader, h1 mh.Multihash) error {
149148

150149
// Multihash reads all the data in r and calculates its multihash.
151150
func (o *Options) Multihash(r io.Reader) (mh.Multihash, error) {
152-
b, err := ioutil.ReadAll(r)
153-
if err != nil {
154-
return nil, err
155-
}
156-
157-
return mh.Sum(b, o.AlgorithmCode, o.Length)
151+
return mh.SumStream(r, o.AlgorithmCode, o.Length)
158152
}

sum.go

+26-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package multihash
33
import (
44
"errors"
55
"fmt"
6+
"hash"
7+
"io"
68

79
mhreg "github.com/multiformats/go-multihash/core"
810
)
@@ -13,8 +15,8 @@ var ErrSumNotSupported = mhreg.ErrSumNotSupported
1315
var ErrLenTooLarge = errors.New("requested length was too large for digest")
1416

1517
// 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.
1820
func Sum(data []byte, code uint64, length int) (Multihash, error) {
1921
// Get the algorithm.
2022
hasher, err := GetHasher(code)
@@ -25,6 +27,28 @@ func Sum(data []byte, code uint64, length int) (Multihash, error) {
2527
// Feed data in.
2628
hasher.Write(data)
2729

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) {
2852
// Compute final hash.
2953
// A new slice is allocated. FUTURE: see other comment below about allocation, and review together with this line to try to improve.
3054
sum := hasher.Sum(nil)

0 commit comments

Comments
 (0)