diff --git a/helper/hashcode/hashcode.go b/helper/hashcode/hashcode.go index 64d8263e6..6ccc52318 100644 --- a/helper/hashcode/hashcode.go +++ b/helper/hashcode/hashcode.go @@ -1,6 +1,8 @@ package hashcode import ( + "bytes" + "fmt" "hash/crc32" ) @@ -20,3 +22,14 @@ func String(s string) int { // v == MinInt return 0 } + +// Strings hashes a list of strings to a unique hashcode. +func Strings(strings []string) string { + var buf bytes.Buffer + + for _, s := range strings { + buf.WriteString(fmt.Sprintf("%s-", s)) + } + + return fmt.Sprintf("%d", String(buf.String())) +} diff --git a/helper/hashcode/hashcode_test.go b/helper/hashcode/hashcode_test.go index 1b521823f..4b90431ba 100644 --- a/helper/hashcode/hashcode_test.go +++ b/helper/hashcode/hashcode_test.go @@ -15,6 +15,17 @@ func TestString(t *testing.T) { } } +func TestStrings(t *testing.T) { + v := []string{"hello", ",", "world"} + expected := Strings(v) + for i := 0; i < 100; i++ { + actual := Strings(v) + if actual != expected { + t.Fatalf("bad: %#v\n\t%#v", actual, expected) + } + } +} + func TestString_positiveIndex(t *testing.T) { // "2338615298" hashes to uint32(2147483648) which is math.MinInt32 ips := []string{"192.168.1.3", "192.168.1.5", "2338615298"}