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
}
