github.com/uber/kraken@v0.1.4/core/digester.go (about) 1 // Copyright (c) 2016-2019 Uber Technologies, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package core 15 16 import ( 17 "crypto" 18 "encoding/hex" 19 "hash" 20 "io" 21 ) 22 23 const ( 24 // SHA256 is the only algorithm supported. 25 SHA256 = "sha256" 26 ) 27 28 // Digester calculates the digest of data stream. 29 type Digester struct { 30 hash hash.Hash 31 } 32 33 // NewDigester instantiates and returns a new Digester object. 34 func NewDigester() *Digester { 35 return &Digester{ 36 hash: crypto.SHA256.New(), 37 } 38 } 39 40 // Digest returns the digest of existing data. 41 func (d *Digester) Digest() Digest { 42 digest, err := NewSHA256DigestFromHex(hex.EncodeToString(d.hash.Sum(nil))) 43 if err != nil { 44 // This should never fail. 45 panic(err) 46 } 47 return digest 48 } 49 50 // FromReader returns the digest of data from reader. 51 func (d Digester) FromReader(rd io.Reader) (Digest, error) { 52 if _, err := io.Copy(d.hash, rd); err != nil { 53 return Digest{}, err 54 } 55 56 return d.Digest(), nil 57 } 58 59 // FromBytes digests the input and returns a Digest. 60 func (d Digester) FromBytes(p []byte) (Digest, error) { 61 if _, err := d.hash.Write(p); err != nil { 62 return Digest{}, err 63 } 64 65 return d.Digest(), nil 66 } 67 68 // Tee allows d to calculate a digest of r while the caller reads from the 69 // returned reader. 70 func (d Digester) Tee(r io.Reader) io.Reader { 71 return io.TeeReader(r, d.hash) 72 }