github.com/biogo/biogo@v1.0.4/util/files.go (about)

     1  // Copyright ©2011-2012 The bíogo Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package util
     6  
     7  import (
     8  	"errors"
     9  	"hash"
    10  	"io"
    11  	"os"
    12  )
    13  
    14  const (
    15  	bufferLen = 1 << 15
    16  )
    17  
    18  var buffer = make([]byte, bufferLen)
    19  
    20  // Hash returns the h hash sum of file f and any error. The hash is not reset on return,
    21  // so if individual files are to be hashed with the same h, it should be reset.
    22  func Hash(h hash.Hash, f *os.File) (sum []byte, err error) {
    23  	fi, err := f.Stat()
    24  	if err != nil || fi.IsDir() {
    25  		return nil, errors.New("util: file is a directory")
    26  	}
    27  
    28  	s := io.NewSectionReader(f, 0, fi.Size())
    29  
    30  	for n, buffer := 0, make([]byte, bufferLen); err == nil; {
    31  		n, err = s.Read(buffer)
    32  		h.Write(buffer[:n])
    33  	}
    34  	if err == io.EOF {
    35  		err = nil
    36  	}
    37  
    38  	sum = h.Sum(nil)
    39  
    40  	return
    41  }