aboutsummaryrefslogtreecommitdiff
path: root/internal/murmurhash2/murmurhash2.go
blob: c728f9324ba35e8adcc968e6caf022fb25b76b15 (about) (plain) (blame)
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
// Package murmurhash2 provides a non-cryptographic hash.
package murmurhash2

import "encoding/binary"

// Sum32 computes the MurmurHash2 value for key with the provided seed.
func Sum32(key []byte, seed uint32) uint32 {
	const (
		m uint32 = 0x5bd1e995
		r uint32 = 24
	)

	h := seed ^ uint32(len(key))
	i := 0
	for len(key)-i >= 4 {
		k := binary.LittleEndian.Uint32(key[i:])
		k *= m
		k ^= k >> r
		k *= m

		h *= m
		h ^= k
		i += 4
	}

	switch len(key) - i {
	case 3:
		h ^= uint32(key[i+2]) << 16
		fallthrough
	case 2:
		h ^= uint32(key[i+1]) << 8
		fallthrough
	case 1:
		h ^= uint32(key[i])
		h *= m
	}

	h ^= h >> 13
	h *= m
	h ^= h >> 15
	return h
}