2014-08-21 07:09:40 +02:00
|
|
|
package hashcode
|
|
|
|
|
2015-02-11 20:40:49 +01:00
|
|
|
import (
|
2017-10-20 23:54:23 +02:00
|
|
|
"bytes"
|
|
|
|
"fmt"
|
2015-02-11 20:40:49 +01:00
|
|
|
"hash/crc32"
|
|
|
|
)
|
2014-08-21 07:09:40 +02:00
|
|
|
|
|
|
|
// String hashes a string to a unique hashcode.
|
2015-02-11 19:59:21 +01:00
|
|
|
//
|
|
|
|
// 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.
|
2014-08-21 07:09:40 +02:00
|
|
|
func String(s string) int {
|
2015-02-11 19:59:21 +01:00
|
|
|
v := int(crc32.ChecksumIEEE([]byte(s)))
|
2016-07-01 23:40:07 +02:00
|
|
|
if v >= 0 {
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
if -v >= 0 {
|
2015-02-11 19:59:21 +01:00
|
|
|
return -v
|
|
|
|
}
|
2016-07-01 23:40:07 +02:00
|
|
|
// v == MinInt
|
|
|
|
return 0
|
2014-08-21 07:09:40 +02:00
|
|
|
}
|
2017-10-20 23:54:23 +02:00
|
|
|
|
|
|
|
// 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()))
|
|
|
|
}
|