public
Created

Some basic hash functions for Go. I wrote this as my first attempt at Go.

  • Download Gist
hash.go
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
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
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.