From 7096e4d3da5963248d05045efc9f4c019ec73355 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Fri, 1 Jul 2016 14:40:07 -0700 Subject: [PATCH] Return nonnegative hash if int is 32 bits --- helper/hashcode/hashcode.go | 9 ++++++--- helper/hashcode/hashcode_test.go | 3 ++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/helper/hashcode/hashcode.go b/helper/hashcode/hashcode.go index 214a2f1e5..64d8263e6 100644 --- a/helper/hashcode/hashcode.go +++ b/helper/hashcode/hashcode.go @@ -11,9 +11,12 @@ import ( // and invert it if the result is negative. func String(s string) int { v := int(crc32.ChecksumIEEE([]byte(s))) - if v < 0 { + if v >= 0 { + return v + } + if -v >= 0 { return -v } - - return v + // v == MinInt + return 0 } diff --git a/helper/hashcode/hashcode_test.go b/helper/hashcode/hashcode_test.go index 47bc85760..1b521823f 100644 --- a/helper/hashcode/hashcode_test.go +++ b/helper/hashcode/hashcode_test.go @@ -16,7 +16,8 @@ func TestString(t *testing.T) { } func TestString_positiveIndex(t *testing.T) { - ips := []string{"192.168.1.3", "192.168.1.5"} + // "2338615298" hashes to uint32(2147483648) which is math.MinInt32 + ips := []string{"192.168.1.3", "192.168.1.5", "2338615298"} for _, ip := range ips { if index := String(ip); index < 0 { t.Fatalf("Bad Index %#v for ip %s", index, ip)