11 // Compute the MD5 digest of a data block (consisting of buf1 + buf2 +
12 // all bytes readable from rdr). If all data is read successfully,
13 // return DiskHashError or CollisionError depending on whether it
14 // matches expectMD5. If an error occurs while reading, return that
17 // "content has expected MD5" is called a collision because this
18 // function is used in cases where we have another block in hand with
19 // the given MD5 but different content.
20 func collisionOrCorrupt(expectMD5 string, buf1, buf2 []byte, rdr io.Reader) error {
21 outcome := make(chan error)
22 data := make(chan []byte, 1)
28 if fmt.Sprintf("%x", h.Sum(nil)) == expectMD5 {
29 outcome <- CollisionError
31 outcome <- DiskHashError
39 for rdr != nil && err == nil {
40 buf := make([]byte, 1<<18)
42 n, err = rdr.Read(buf)
46 if rdr != nil && err != io.EOF {
53 func compareReaderWithBuf(ctx context.Context, rdr io.Reader, expect []byte, hash string) error {
55 if bufLen > len(expect) && len(expect) > 0 {
56 // No need for bufLen to be longer than
57 // expect, except that len(buf)==0 would
58 // prevent us from handling empty readers the
59 // same way as non-empty readers: reading 0
60 // bytes at a time never reaches EOF.
63 buf := make([]byte, bufLen)
66 // Loop invariants: all data read so far matched what
67 // we expected, and the first N bytes of cmp are
68 // expected to equal the next N bytes read from
71 ready := make(chan bool)
75 n, err = rdr.Read(buf)
83 if n > len(cmp) || bytes.Compare(cmp[:n], buf[:n]) != 0 {
84 return collisionOrCorrupt(hash, expect[:len(expect)-len(cmp)], buf[:n], rdr)
89 return collisionOrCorrupt(hash, expect[:len(expect)-len(cmp)], nil, nil)
92 } else if err != nil {