Skip to content

Commit

Permalink
Return nonnegative hash if int is 32 bits
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Jul 1, 2016
1 parent 3b73213 commit 7096e4d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
9 changes: 6 additions & 3 deletions helper/hashcode/hashcode.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
3 changes: 2 additions & 1 deletion helper/hashcode/hashcode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 7096e4d

Please sign in to comment.