Merge branch '16809-s3-v4-signature'
[arvados.git] / sdk / go / keepclient / hashcheck.go
index 1706134757fae14a6cc0f0ccecc1a7b6a46a3002..9295c14cc24a47cd38479e19a8aa57dc91c1c42a 100644 (file)
@@ -1,3 +1,7 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: Apache-2.0
+
 package keepclient
 
 import (
@@ -31,7 +35,7 @@ func (this HashCheckingReader) Read(p []byte) (n int, err error) {
                this.Hash.Write(p[:n])
        }
        if err == io.EOF {
-               sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
+               sum := this.Hash.Sum(nil)
                if fmt.Sprintf("%x", sum) != this.Check {
                        err = BadChecksum
                }
@@ -39,8 +43,9 @@ func (this HashCheckingReader) Read(p []byte) (n int, err error) {
        return n, err
 }
 
-// WriteTo writes the entire contents of this.Reader to dest.  Returns
-// BadChecksum if the checksum doesn't match.
+// WriteTo writes the entire contents of this.Reader to dest. Returns
+// BadChecksum if writing is successful but the checksum doesn't
+// match.
 func (this HashCheckingReader) WriteTo(dest io.Writer) (written int64, err error) {
        if writeto, ok := this.Reader.(io.WriterTo); ok {
                written, err = writeto.WriteTo(io.MultiWriter(dest, this.Hash))
@@ -48,13 +53,16 @@ func (this HashCheckingReader) WriteTo(dest io.Writer) (written int64, err error
                written, err = io.Copy(io.MultiWriter(dest, this.Hash), this.Reader)
        }
 
-       sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
+       if err != nil {
+               return written, err
+       }
 
+       sum := this.Hash.Sum(nil)
        if fmt.Sprintf("%x", sum) != this.Check {
-               err = BadChecksum
+               return written, BadChecksum
        }
 
-       return written, err
+       return written, nil
 }
 
 // Close reads all remaining data from the underlying Reader and
@@ -63,14 +71,17 @@ func (this HashCheckingReader) WriteTo(dest io.Writer) (written int64, err error
 func (this HashCheckingReader) Close() (err error) {
        _, err = io.Copy(this.Hash, this.Reader)
 
-       if closer, ok := this.Reader.(io.ReadCloser); ok {
-               err = closer.Close()
+       if closer, ok := this.Reader.(io.Closer); ok {
+               closeErr := closer.Close()
+               if err == nil {
+                       err = closeErr
+               }
        }
-
-       sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
-       if fmt.Sprintf("%x", sum) != this.Check {
-               err = BadChecksum
+       if err != nil {
+               return err
        }
-
-       return err
+       if fmt.Sprintf("%x", this.Hash.Sum(nil)) != this.Check {
+               return BadChecksum
+       }
+       return nil
 }