Skip to content

Commit a5040ec

Browse files
committed
Update hashcode to always generate a positive
1 parent 9d53689 commit a5040ec

2 files changed

Lines changed: 22 additions & 8 deletions

File tree

‎helper/hashcode/hashcode.go‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
package hashcode
22

3-
import (
4-
"hash/crc32"
5-
)
3+
import "hash/crc32"
64

75
// String hashes a string to a unique hashcode.
6+
//
7+
// crc32 returns a uint32, but for our use we need
8+
// and non negative integer. Here we cast to an integer
9+
// and invert it if the result is negative.
810
func String(s string) int {
9-
return int(crc32.ChecksumIEEE([]byte(s)))
11+
v := int(crc32.ChecksumIEEE([]byte(s)))
12+
if v < 0 {
13+
return -v
14+
}
15+
return v
1016
}

‎helper/hashcode/hashcode_test.go‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
11
package hashcode
22

3-
import (
4-
"testing"
5-
)
3+
import "testing"
64

75
func TestString(t *testing.T) {
86
v := "hello, world"
97
expected := String(v)
108
for i := 0; i < 100; i++ {
119
actual := String(v)
1210
if actual != expected {
13-
t.Fatalf("bad: %#v", actual)
11+
t.Fatalf("bad: %#v\n\t%#v", actual, expected)
12+
}
13+
}
14+
}
15+
16+
func TestString_positiveIndex(t *testing.T) {
17+
ips := []string{"192.168.1.3", "192.168.1.5"}
18+
for _, ip := range ips {
19+
index := String(ip)
20+
if index < 0 {
21+
t.Fatalf("Bad Index %#v for ip %s", index, ip)
1422
}
1523
}
1624
}

0 commit comments

Comments
 (0)