github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/hash/multi.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package hash 19 20 import ( 21 "encoding/hex" 22 "fmt" 23 "hash" 24 "io" 25 ) 26 27 func NewMultiHash(r io.Reader, algorithms ...string) (map[string]string, error) { 28 hashers := map[string]hash.Hash{} 29 30 // Instantiate hashers 31 for _, algo := range algorithms { 32 // Create an hasher instance. 33 h, err := NewHasher(algo) 34 if err != nil { 35 return nil, fmt.Errorf("unable to initialize %q algorithm: %w", algo, err) 36 } 37 38 // Assign to hashers. 39 hashers[algo] = h 40 } 41 42 // Copy to all hashers 43 _, err := io.Copy(io.MultiWriter(hashToMultiWriter(hashers)), r) 44 if err != nil { 45 return nil, err 46 } 47 48 // Finalize 49 res := make(map[string]string) 50 for algo, v := range hashers { 51 res[algo] = hex.EncodeToString(v.Sum(nil)) 52 } 53 54 // No error 55 return res, nil 56 } 57 58 // ----------------------------------------------------------------------------- 59 60 func hashToMultiWriter(hashers map[string]hash.Hash) io.Writer { 61 w := make([]io.Writer, 0, len(hashers)) 62 for _, v := range hashers { 63 w = append(w, v) 64 } 65 return io.MultiWriter(w...) 66 }