gopkg.in/juju/charm.v6-unstable@v6.0.0-20171026192109-50d0c219b496/resource/fingerprint.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the LGPLv3, see LICENCE file for details.
     3  
     4  package resource
     5  
     6  import (
     7  	stdhash "hash"
     8  	"io"
     9  
    10  	"github.com/juju/errors"
    11  	"github.com/juju/utils/hash"
    12  )
    13  
    14  var newHash, validateSum = hash.SHA384()
    15  
    16  // Fingerprint represents the unique fingerprint value of a resource's data.
    17  type Fingerprint struct {
    18  	hash.Fingerprint
    19  }
    20  
    21  // NewFingerprint returns wraps the provided raw fingerprint bytes.
    22  // This function roundtrips with Fingerprint.Bytes().
    23  func NewFingerprint(raw []byte) (Fingerprint, error) {
    24  	fp, err := hash.NewFingerprint(raw, validateSum)
    25  	if err != nil {
    26  		return Fingerprint{}, errors.Trace(err)
    27  	}
    28  	return Fingerprint{fp}, nil
    29  }
    30  
    31  // ParseFingerprint returns wraps the provided raw fingerprint string.
    32  // This function roundtrips with Fingerprint.String().
    33  func ParseFingerprint(raw string) (Fingerprint, error) {
    34  	fp, err := hash.ParseHexFingerprint(raw, validateSum)
    35  	if err != nil {
    36  		return Fingerprint{}, errors.Trace(err)
    37  	}
    38  	return Fingerprint{fp}, nil
    39  }
    40  
    41  // GenerateFingerprint returns the fingerprint for the provided data.
    42  func GenerateFingerprint(reader io.Reader) (Fingerprint, error) {
    43  	fp, err := hash.GenerateFingerprint(reader, newHash)
    44  	if err != nil {
    45  		return Fingerprint{}, errors.Trace(err)
    46  	}
    47  	return Fingerprint{fp}, nil
    48  }
    49  
    50  // Fingerprint is a hash that may be used to generate fingerprints.
    51  type FingerprintHash struct {
    52  	stdhash.Hash
    53  }
    54  
    55  // NewFingerprintHash returns a hash that may be used to create fingerprints.
    56  func NewFingerprintHash() *FingerprintHash {
    57  	return &FingerprintHash{
    58  		Hash: newHash(),
    59  	}
    60  }
    61  
    62  // Fingerprint returns the current fingerprint of the hash.
    63  func (fph FingerprintHash) Fingerprint() Fingerprint {
    64  	fp := hash.NewValidFingerprint(fph)
    65  	return Fingerprint{fp}
    66  }