Moved the implementation of this hash table from `tools/dsa` #1. Reviewed-on: #1 Co-authored-by: M.V. Hutz <git@maximhutz.me> Co-committed-by: M.V. Hutz <git@maximhutz.me>
35 lines
815 B
Go
35 lines
815 B
Go
package cuckoo_test
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/binary"
|
|
"fmt"
|
|
"io"
|
|
|
|
"git.maximhutz.com/tools/go-cuckoo"
|
|
)
|
|
|
|
func NewStringHash(seed uint64) cuckoo.Hash[string] {
|
|
key := binary.LittleEndian.AppendUint64(nil, seed)
|
|
hash := hmac.New(sha256.New, key)
|
|
|
|
return func(key string) uint64 {
|
|
hash.Reset()
|
|
// This will never return an error, as part of the [hash.Hash] contract. We
|
|
// can safely ignore it.
|
|
(io.WriteString(hash, key))
|
|
return binary.LittleEndian.Uint64(hash.Sum(nil))
|
|
}
|
|
}
|
|
|
|
func ExampleHash_stringHash() {
|
|
hash := NewStringHash(1)
|
|
fmt.Printf("Digest 'Hello, world!': %x\n", hash("Hello, world!"))
|
|
fmt.Printf("Digest 'Hello, world?': %x\n", hash("Hello, world?"))
|
|
|
|
// Output:
|
|
// Digest 'Hello, world!': dc6602d6edcdf549
|
|
// Digest 'Hello, world?': 432c2ddc1ae9f14b
|
|
}
|