github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/util/hash.go (about) 1 // Copyright 2017 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package util 12 13 import ( 14 "hash/crc32" 15 16 "github.com/cockroachdb/errors" 17 ) 18 19 // CRC32 computes the Castagnoli CRC32 of the given data. 20 func CRC32(data []byte) uint32 { 21 hash := crc32.New(crc32.MakeTable(crc32.Castagnoli)) 22 if _, err := hash.Write(data); err != nil { 23 panic(errors.Wrap(err, `"It never returns an error." -- https://golang.org/pkg/hash`)) 24 } 25 return hash.Sum32() 26 } 27 28 // Magic FNV Base constant as suitable for a FNV-64 hash. 29 const fnvBase = uint64(14695981039346656037) 30 const fnvPrime = 1099511628211 31 32 // FNV64 encapsulates the hash state. 33 type FNV64 struct { 34 sum uint64 35 } 36 37 // MakeFNV64 initializes a new FNV64 hash state. 38 func MakeFNV64() FNV64 { 39 return FNV64{sum: fnvBase} 40 } 41 42 // Init initializes FNV64 to starting value. 43 func (f *FNV64) Init() { 44 f.sum = fnvBase 45 } 46 47 // IsInitialized returns true if the hash struct was initialized, which happens 48 // automatically when created through MakeFNV64 above. 49 func (f *FNV64) IsInitialized() bool { 50 return f.sum != 0 51 } 52 53 // Add modifies the underlying FNV64 state by accumulating the given integer 54 // hash to the existing state. 55 func (f *FNV64) Add(c uint64) { 56 f.sum *= fnvPrime 57 f.sum ^= c 58 } 59 60 // Sum returns the hash value accumulated till now. 61 func (f *FNV64) Sum() uint64 { 62 return f.sum 63 }