-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathhash.go
58 lines (48 loc) · 1.5 KB
/
hash.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
// Copyright 2017 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package util
import (
"hash/crc32"
"github.com/cockroachdb/errors"
)
// CRC32 computes the Castagnoli CRC32 of the given data.
func CRC32(data []byte) uint32 {
hash := crc32.New(crc32.MakeTable(crc32.Castagnoli))
if _, err := hash.Write(data); err != nil {
panic(errors.Wrap(err, `"It never returns an error." -- https://golang.org/pkg/hash`))
}
return hash.Sum32()
}
// Magic FNV Base constant as suitable for a FNV-64 hash.
const fnvBase = uint64(14695981039346656037)
const fnvPrime = 1099511628211
// FNV64 encapsulates the hash state.
type FNV64 struct {
sum uint64
}
// NewFNV64 initializes a new FNV64 hash state.
func NewFNV64() FNV64 {
return FNV64{sum: fnvBase}
}
// IsInitialized returns true if the hash struct was initialized, which happens
// automatically when created through NewFNV64 above.
func (f *FNV64) IsInitialized() bool {
return f.sum != 0
}
// Add modifies the underlying FNV64 state by accumulating the given integer
// hash to the existing state.
func (f *FNV64) Add(c uint64) {
f.sum *= fnvPrime
f.sum ^= c
}
// Sum returns the hash value accumulated so now.
func (f *FNV64) Sum() uint64 {
return f.sum
}