Skip to content

Instantly share code, notes, and snippets.

@giautm
Created October 26, 2018 13:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giautm/d79994acd796f3065903eccbc8d6e09b to your computer and use it in GitHub Desktop.
Save giautm/d79994acd796f3065903eccbc8d6e09b to your computer and use it in GitHub Desktop.
Golang implement of `java.lang.String` hashCode() https://en.wikipedia.org/wiki/Java_hashCode()
package hashcode
import "hash"
const Size = 4
func NewHash() hash.Hash32 {
var s sum32 = 0
return &s
}
type sum32 uint32
func (sum32) BlockSize() int { return 1 }
func (sum32) Size() int { return Size }
func (h *sum32) Reset() { *h = 0 }
func (h sum32) Sum32() uint32 { return uint32(h) }
func (h sum32) Sum(in []byte) []byte {
s := h.Sum32()
return append(in, byte(s>>24), byte(s>>16), byte(s>>8), byte(s))
}
func (h *sum32) Write(p []byte) (n int, err error) {
s := h.Sum32()
for _, pp := range p {
s = 31*s + uint32(pp)
}
*h = sum32(s)
return len(p), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment