Update hashcode to always generate a positive

This commit is contained in:
Clint Shryock 2015-02-11 10:59:21 -08:00
parent 9d53689f11
commit a5040ecc03
2 changed files with 22 additions and 8 deletions

View File

@ -1,10 +1,16 @@
package hashcode package hashcode
import ( import "hash/crc32"
"hash/crc32"
)
// String hashes a string to a unique hashcode. // String hashes a string to a unique hashcode.
//
// crc32 returns a uint32, but for our use we need
// and non negative integer. Here we cast to an integer
// and invert it if the result is negative.
func String(s string) int { func String(s string) int {
return int(crc32.ChecksumIEEE([]byte(s))) v := int(crc32.ChecksumIEEE([]byte(s)))
if v < 0 {
return -v
}
return v
} }

View File

@ -1,8 +1,6 @@
package hashcode package hashcode
import ( import "testing"
"testing"
)
func TestString(t *testing.T) { func TestString(t *testing.T) {
v := "hello, world" v := "hello, world"
@ -10,7 +8,17 @@ func TestString(t *testing.T) {
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
actual := String(v) actual := String(v)
if actual != expected { if actual != expected {
t.Fatalf("bad: %#v", actual) t.Fatalf("bad: %#v\n\t%#v", actual, expected)
}
}
}
func TestString_positiveIndex(t *testing.T) {
ips := []string{"192.168.1.3", "192.168.1.5"}
for _, ip := range ips {
index := String(ip)
if index < 0 {
t.Fatalf("Bad Index %#v for ip %s", index, ip)
} }
} }
} }