Adds hash_test code

This commit is contained in:
2022-03-21 22:44:21 -07:00
parent 4f515fba3b
commit 4d3bbc0c88
3 changed files with 82 additions and 0 deletions

35
hash.go Normal file
View File

@@ -0,0 +1,35 @@
package go_colorhash
import (
"crypto/md5"
"encoding/binary"
"io"
)
const MaxUint = ^uint(0)
const MaxInt = int(MaxUint >> 1)
func HashString(s string) int {
h := md5.New()
io.WriteString(h, s)
hashb := h.Sum(nil)
hashb = hashb[len(hashb)-8:]
lsb := binary.BigEndian.Uint64(hashb)
sint := int(lsb)
if sint < 0 {
sint = sint + MaxInt
}
return sint
}
func HashBytes(r io.Reader) int {
h := md5.New()
io.Copy(h, r)
hashb := h.Sum(nil)
hashb = hashb[len(hashb)-8:]
lsb := binary.BigEndian.Uint64(hashb)
sint := int(lsb)
if sint < 0 {
sint = sint + MaxInt
}
return sint
}