All checks were successful
CI / Check PR Title (push) Has been skipped
CI / Makefile Lint (push) Successful in 47s
CI / Go Lint (push) Successful in 51s
CI / Markdown Lint (push) Successful in 46s
CI / Unit Tests (push) Successful in 47s
CI / Fuzz Tests (push) Successful in 1m19s
CI / Mutation Tests (push) Successful in 1m36s
## Description Currently, the name of `bucket` is a bit confusing, because it is considered a 'table' in literature (as well as the whole hash table). A `bucket` is better described as a 'subtable', which is used by the total hash table to perform cuckoo hashing. In addition, the constructors `NewTable`, `NewTableBy`, and `NewCustomTable` were given shorter names, because the package name `cuckoo` already implies that `New*` would create a hash table with cuckoo hashing. This package has one use-case, and so it unambiguous what constructors produce. ## Changes - `NewTable` -> `New` - `NewTableBy` -> `NewBy` - `NewCustomTable` -> `NewCustom` - `bucket` -> `subtable` ### Design Decisions - I would have renamed `Table` and `subtable` to map equivalents, but 'submap' implies that a certain subsection of the map is contained within it, which isn't quite right. - I chose not to go with `Map` and `table`, because of the split naming convention. ## Checklist - [x] Tests pass - [x] Docs updated Reviewed-on: #22 Co-authored-by: M.V. Hutz <git@maximhutz.me> Co-committed-by: M.V. Hutz <git@maximhutz.me>
49 lines
1.3 KiB
Go
49 lines
1.3 KiB
Go
package cuckoo_test
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.maximhutz.com/tools/go-cuckoo"
|
|
)
|
|
|
|
// This example demonstrates what happens when EqualFunc and Hash disagree on
|
|
// equality. Although 'isEqual' only compares user IDs, but the hashes use the
|
|
// entire 'User' object. So, two objects with the same ID but different names
|
|
// hash to different slots, so the table cannot find them.
|
|
func ExampleEqualFunc_badEqualFunc() {
|
|
type User struct{ ID, Name string }
|
|
|
|
makeHash := func(seed uint64) cuckoo.Hash[User] {
|
|
return func(u User) uint64 {
|
|
digest := seed
|
|
|
|
for _, c := range u.ID + u.Name {
|
|
digest ^= uint64(c)
|
|
}
|
|
|
|
return digest
|
|
}
|
|
}
|
|
|
|
// Two users with the same ID are equal.
|
|
isEqual := func(a, b User) bool { return a.ID == b.ID }
|
|
|
|
userbase := cuckoo.NewCustom[User, bool](makeHash(1), makeHash(2), isEqual)
|
|
|
|
(userbase.Put(User{"1", "Robert Doe"}, true))
|
|
|
|
fmt.Println("Has Robert?", userbase.Has(User{"1", "Robert Doe"}))
|
|
fmt.Println("Has Johanna?", userbase.Has(User{"2", "Johanna Smith"}))
|
|
|
|
// The hashes are different, so even though the equal function returns true,
|
|
// the table does not recognize it.
|
|
fmt.Println("Equal?", isEqual(User{"1", "Rob Doe"}, User{"1", "Robert Doe"}))
|
|
fmt.Println("Has Rob?", userbase.Has(User{"1", "Rob Doe"}))
|
|
|
|
// Output:
|
|
// Has Robert? true
|
|
// Has Johanna? false
|
|
// Equal? true
|
|
// Has Rob? false
|
|
}
|