hashcode: "Strings" function for hashing slices of strings
This commit is contained in:
parent
314ef8b110
commit
013df9350b
|
@ -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()))
|
||||
}
|
||||
|
|
|
@ -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"}
|
||||
|
|
Loading…
Reference in New Issue