Created
October 26, 2018 13:50
-
-
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()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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