Created
May 10, 2013 18:51
-
-
Save Chase-san/5556547 to your computer and use it in GitHub Desktop.
Some basic hash functions for Go. I wrote this as my first attempt at Go.
This file contains 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 hash | |
type Hasher interface { | |
Update(uint8) | |
UpdateArray([]uint8) | |
Hash() uint32 | |
Reset() | |
} | |
const ( | |
fnvprime uint32 = 0x01000193 | |
fnvoffset uint32 = 0x811C9DC5 | |
) | |
// Fowler Noll Vo hash function | |
type FowlerNollVo struct { | |
hash uint32 | |
} | |
func NewFowlerNollVo() *FowlerNollVo { | |
return &FowlerNollVo{fnvoffset} | |
} | |
func (h *FowlerNollVo) Update(b uint8) { | |
h.hash ^= uint32(b) | |
h.hash *= fnvprime | |
} | |
func (h *FowlerNollVo) UpdateArray(b []uint8) { | |
for _,e := range b { | |
h.hash ^= uint32(e) | |
h.hash *= fnvprime | |
} | |
} | |
func (h *FowlerNollVo) Hash() uint32 { | |
return h.hash | |
} | |
func (h *FowlerNollVo) Reset() { | |
h.hash = fnvoffset | |
} | |
// Jenkins hash function | |
type Jenkins struct { | |
hash uint32 | |
} | |
func NewJenkins() *Jenkins { | |
return &Jenkins{} | |
} | |
func (h *Jenkins) Update(b uint8) { | |
h.hash += uint32(b) | |
h.hash += (h.hash << 10) | |
h.hash ^= (h.hash >> 6) | |
} | |
func (h *Jenkins) UpdateArray(b []uint8) { | |
for _,e := range b { | |
h.hash += uint32(e) | |
h.hash += (h.hash << 10) | |
h.hash ^= (h.hash >> 6) | |
} | |
} | |
func (h *Jenkins) Hash() uint32 { | |
hout := h.hash | |
hout += hout << 3 | |
hout ^= hout >> 11 | |
hout += hout << 15 | |
return hout | |
} | |
func (h *Jenkins) Reset() { | |
h.hash = 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment