github.com/opentofu/opentofu@v1.7.1/internal/legacy/helper/hashcode/hashcode.go (about) 1 // Copyright (c) The OpenTofu Authors 2 // SPDX-License-Identifier: MPL-2.0 3 // Copyright (c) 2023 HashiCorp, Inc. 4 // SPDX-License-Identifier: MPL-2.0 5 6 package hashcode 7 8 import ( 9 "bytes" 10 "fmt" 11 "hash/crc32" 12 ) 13 14 // String hashes a string to a unique hashcode. 15 // Returns a non-negative integer representing the hashcode of the string. 16 func String(s string) int { 17 // crc32 returns an uint32, so we need to massage it into an int. 18 crc := crc32.ChecksumIEEE([]byte(s)) 19 // We need to first squash the result to 32 bits, embracing the overflow 20 // to ensure that there is no difference between 32 and 64-bit 21 // platforms. 22 squashed := int32(crc) 23 // convert into a generic int that is sized as per the architecture 24 systemSized := int(squashed) 25 26 // If the integer is negative, we return the absolute value of the 27 // integer. This is because we want to return a non-negative integer 28 if systemSized >= 0 { 29 return systemSized 30 } 31 if -systemSized >= 0 { 32 return -systemSized 33 } 34 // systemSized == MinInt 35 return 0 36 } 37 38 // Strings hashes a list of strings to a unique hashcode. 39 func Strings(strings []string) string { 40 var buf bytes.Buffer 41 42 for _, s := range strings { 43 buf.WriteString(fmt.Sprintf("%s-", s)) 44 } 45 46 return fmt.Sprintf("%d", String(buf.String())) 47 }