fix: Update ObjMetadataSet.Hash to not error

This commit is contained in:
Karl Isenberg 2022-01-19 11:10:04 -08:00
parent 1dddc9ee64
commit a42a1517d4
2 changed files with 10 additions and 27 deletions

View File

@ -132,32 +132,19 @@ func (setA ObjMetadataSet) Diff(setB ObjMetadataSet) ObjMetadataSet {
// Hash the objects in the set by serializing, sorting, concatonating, and // Hash the objects in the set by serializing, sorting, concatonating, and
// hashing the result with the 32-bit FNV-1a algorithm. // hashing the result with the 32-bit FNV-1a algorithm.
func (setA ObjMetadataSet) Hash() (string, error) { func (setA ObjMetadataSet) Hash() string {
objStrs := make([]string, 0, len(setA)) objStrs := make([]string, 0, len(setA))
for _, obj := range setA { for _, obj := range setA {
objStrs = append(objStrs, obj.String()) objStrs = append(objStrs, obj.String())
} }
hashInt, err := calcHash(objStrs) sort.Strings(objStrs)
if err != nil {
return "", err
}
return strconv.FormatUint(uint64(hashInt), 16), nil
}
// calcHash returns an unsigned int32 representing the hash
// of the obj metadata strings. If there is an error writing bytes to
// the hash, then the error is returned; nil is returned otherwise.
// Used to quickly identify the set of resources in the inventory object.
func calcHash(objs []string) (uint32, error) {
sort.Strings(objs)
h := fnv.New32a() h := fnv.New32a()
for _, obj := range objs { for _, obj := range objStrs {
_, err := h.Write([]byte(obj)) // Hash32.Write never returns an error
if err != nil { // https://pkg.go.dev/hash#pkg-types
return uint32(0), err _, _ = h.Write([]byte(obj))
} }
} return strconv.FormatUint(uint64(h.Sum32()), 16)
return h.Sum32(), nil
} }
// ToMap returns the set as a map, with objMeta keys and empty struct values. // ToMap returns the set as a map, with objMeta keys and empty struct values.

View File

@ -6,6 +6,7 @@ package object
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
) )
@ -214,13 +215,8 @@ func TestObjMetadataSetHash(t *testing.T) {
for name, tc := range tests { for name, tc := range tests {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
actual, err := tc.objs.Hash() actual := tc.objs.Hash()
if err != nil { assert.Equal(t, tc.expected, actual)
t.Fatalf("Received unexpected error: %s", err)
}
if tc.expected != actual {
t.Errorf("Hash expected (%s), got (%s)", tc.expected, actual)
}
}) })
} }
} }