github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/legacy/helper/hashcode/hashcode.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package hashcode 5 6 import ( 7 "bytes" 8 "fmt" 9 "hash/crc32" 10 ) 11 12 // String hashes a string to a unique hashcode. 13 // 14 // crc32 returns a uint32, but for our use we need 15 // a non negative integer. Here we cast to an integer 16 // and invert it if the result is negative. 17 func String(s string) int { 18 v := int(crc32.ChecksumIEEE([]byte(s))) 19 if v >= 0 { 20 return v 21 } 22 if -v >= 0 { 23 return -v 24 } 25 // v == MinInt 26 return 0 27 } 28 29 // Strings hashes a list of strings to a unique hashcode. 30 func Strings(strings []string) string { 31 var buf bytes.Buffer 32 33 for _, s := range strings { 34 buf.WriteString(fmt.Sprintf("%s-", s)) 35 } 36 37 return fmt.Sprintf("%d", String(buf.String())) 38 }