1 Commits

Author SHA1 Message Date
39548b4332 feat!: Drop returns bool, Put doesn't stack-overflow (#21)
All checks were successful
CI / Check PR Title (push) Has been skipped
CI / Go Lint (push) Successful in 58s
CI / Makefile Lint (push) Successful in 55s
CI / Markdown Lint (push) Successful in 34s
CI / Unit Tests (push) Successful in 54s
CI / Fuzz Tests (push) Successful in 1m26s
CI / Mutation Tests (push) Successful in 1m11s
## Description

Closes #11.

## Changes

### Design Decisions

## Checklist

- [ ] Tests pass
- [ ] Docs updated

Reviewed-on: #21
Co-authored-by: M.V. Hutz <git@maximhutz.me>
Co-committed-by: M.V. Hutz <git@maximhutz.me>
2026-04-17 01:31:01 +00:00
7 changed files with 69 additions and 70 deletions

View File

@@ -75,9 +75,9 @@ func FuzzInsertLookup(f *testing.F) {
delete(expected, step.key)
_, ok = actual.Get(step.key)
assert.True(ok)
assert.False(ok)
} else {
_, err := actual.Put(step.key, step.value)
err := actual.Put(step.key, step.value)
assert.NoError(err)
expected[step.key] = step.value

View File

@@ -23,7 +23,7 @@ func TestLoad(t *testing.T) {
table := New[int, bool](Capacity(8))
for i := range 16 {
_, err := table.Put(i, true)
err := table.Put(i, true)
assert.NoError(err)
assert.Equal(float64(table.Size())/float64(table.TotalCapacity()), table.load())
}

View File

@@ -25,7 +25,7 @@ func TestAddItem(t *testing.T) {
key, value := 0, true
table := cuckoo.New[int, bool]()
_, err := table.Put(key, value)
err := table.Put(key, value)
assert.NoError(err)
assert.Equal(1, table.Size())
@@ -38,7 +38,7 @@ func TestPutOverwrite(t *testing.T) {
table := cuckoo.New[int, int]()
(table.Put(key, value))
_, err := table.Put(key, newValue)
err := table.Put(key, newValue)
assert.NoError(err)
assert.Equal(1, table.Size())
@@ -52,9 +52,9 @@ func TestSameHash(t *testing.T) {
hash := func(int) uint64 { return 0 }
table := cuckoo.NewCustom[int, bool](hash, hash, cuckoo.DefaultEqualFunc[int])
_, errA := table.Put(0, true)
_, errB := table.Put(1, true)
_, errC := table.Put(2, true)
errA := table.Put(0, true)
errB := table.Put(1, true)
errC := table.Put(2, true)
assert.NoError(errA)
assert.NoError(errB)
@@ -76,7 +76,7 @@ func TestResizeCapacity(t *testing.T) {
)
for table.TotalCapacity() == 16 {
_, err := table.Put(rand.Int(), true)
err := table.Put(rand.Int(), true)
assert.NoError(err)
}
@@ -89,7 +89,7 @@ func TestPutMany(t *testing.T) {
for i := range 1_000 {
expected[i] = true
_, err := actual.Put(i, true)
err := actual.Put(i, true)
assert.NoError(err)
}
@@ -103,7 +103,7 @@ func TestGetMany(t *testing.T) {
table := cuckoo.New[int, bool]()
for i := range 1_000 {
_, err := table.Put(i, true)
err := table.Put(i, true)
assert.NoError(err)
}
@@ -167,7 +167,7 @@ func TestPutNoCapacity(t *testing.T) {
cuckoo.Capacity(0),
)
_, err := table.Put(key, value)
err := table.Put(key, value)
assert.NoError(err)
assert.Equal(1, table.Size())
@@ -183,9 +183,9 @@ func TestBadHashCapacity(t *testing.T) {
cuckoo.Capacity(20),
)
_, err1 := table.Put(0, true)
_, err2 := table.Put(1, true)
_, err3 := table.Put(2, true)
err1 := table.Put(0, true)
err2 := table.Put(1, true)
err3 := table.Put(2, true)
assert.NoError(err1)
assert.NoError(err2)
@@ -200,8 +200,8 @@ func TestDropResizeCapacity(t *testing.T) {
cuckoo.Capacity(10),
)
_, err1 := table.Put(0, true)
_, err2 := table.Put(1, true)
err1 := table.Put(0, true)
err2 := table.Put(1, true)
table.Drop(1)
assert.NoError(errors.Join(err1, err2))
@@ -218,7 +218,7 @@ func TestNewTableBy(t *testing.T) {
assert := assert.New(t)
table := cuckoo.NewBy[User, bool](func(u User) string { return u.id })
_, err := table.Put(User{nil, "1", "Robert"}, true)
err := table.Put(User{nil, "1", "Robert"}, true)
assert.NoError(err)
assert.Equal(1, table.Size())

3
doc.go
View File

@@ -5,5 +5,8 @@
// a table with any key type using [NewCustom]. Custom [Hash] functions and
// key comparison are also supported.
//
// NOTE: The [Table] is a look-up structure, and not a source of truth. If
// [ErrBadHash] occurs, the data cannot be restored.
//
// See more: https://en.wikipedia.org/wiki/Cuckoo_hashing
package cuckoo

View File

@@ -10,7 +10,7 @@ import (
func Example_basic() {
table := cuckoo.New[int, string]()
if _, err := table.Put(1, "Hello, World!"); err != nil {
if err := table.Put(1, "Hello, World!"); err != nil {
fmt.Println("Put error:", err)
}

View File

@@ -1,13 +1,13 @@
package cuckoo
// An Entry is a key-value pair.
type Entry[K, V any] struct {
Key K
Value V
// An entry is a key-value pair.
type entry[K, V any] struct {
key K
value V
}
type slot[K, V any] struct {
Entry[K, V]
entry[K, V]
occupied bool
}
@@ -18,81 +18,81 @@ type subtable[K, V any] struct {
compare EqualFunc[K]
}
// location determines where in the bucket a certain key would be placed. If the
// capacity is 0, this will panic.
func (b *subtable[K, V]) location(key K) uint64 {
return b.hash(key) % b.capacity
// location determines where in the subtable a certain key would be placed. If
// the capacity is 0, this will panic.
func (t *subtable[K, V]) location(key K) uint64 {
return t.hash(key) % t.capacity
}
func (b *subtable[K, V]) get(key K) (value V, found bool) {
if b.capacity == 0 {
func (t *subtable[K, V]) get(key K) (value V, found bool) {
if t.capacity == 0 {
return
}
slot := b.slots[b.location(key)]
return slot.Value, slot.occupied && b.compare(slot.Key, key)
slot := t.slots[t.location(key)]
return slot.value, slot.occupied && t.compare(slot.key, key)
}
func (b *subtable[K, V]) drop(key K) (occupied bool) {
if b.capacity == 0 {
func (t *subtable[K, V]) drop(key K) (occupied bool) {
if t.capacity == 0 {
return
}
slot := &b.slots[b.location(key)]
slot := &t.slots[t.location(key)]
if slot.occupied && b.compare(slot.Key, key) {
if slot.occupied && t.compare(slot.key, key) {
slot.occupied = false
b.size--
t.size--
return true
}
return false
}
func (b *subtable[K, V]) resized(capacity uint64) *subtable[K, V] {
func (t *subtable[K, V]) resized(capacity uint64) *subtable[K, V] {
return &subtable[K, V]{
slots: make([]slot[K, V], capacity),
capacity: capacity,
hash: b.hash,
compare: b.compare,
hash: t.hash,
compare: t.compare,
}
}
func (b *subtable[K, V]) update(key K, value V) (updated bool) {
if b.capacity == 0 {
func (t *subtable[K, V]) update(key K, value V) (updated bool) {
if t.capacity == 0 {
return
}
slot := &b.slots[b.location(key)]
slot := &t.slots[t.location(key)]
if slot.occupied && b.compare(slot.Key, key) {
slot.Value = value
if slot.occupied && t.compare(slot.key, key) {
slot.value = value
return true
}
return false
}
func (b *subtable[K, V]) insert(insertion Entry[K, V]) (evicted Entry[K, V], eviction bool) {
if b.capacity == 0 {
func (t *subtable[K, V]) insert(insertion entry[K, V]) (evicted entry[K, V], eviction bool) {
if t.capacity == 0 {
return insertion, true
}
slot := &b.slots[b.location(insertion.Key)]
slot := &t.slots[t.location(insertion.key)]
if !slot.occupied {
slot.Entry = insertion
slot.entry = insertion
slot.occupied = true
b.size++
t.size++
return
}
if b.compare(slot.Key, insertion.Key) {
slot.Value = insertion.Value
if t.compare(slot.key, insertion.key) {
slot.value = insertion.value
return
}
insertion, slot.Entry = slot.Entry, insertion
insertion, slot.entry = slot.entry, insertion
return insertion, true
}

View File

@@ -9,7 +9,7 @@ import (
)
// ErrBadHash occurs when the hashes given to a [Table] cause too many key
// collisions. Try rebuilding the table using:
// collisions. Discard the old table, rebuild it from your source data, and try:
//
// 1. Different hash seeds. Equal seeds produce equal hash functions, which
// always cycle.
@@ -57,12 +57,12 @@ func (t *Table[K, V]) load() float64 {
// insert attempts to put/update an entry in the table, without modifying the
// size of the table. Returns a displaced entry and 'homeless = true' if an
// entry could not be placed after exhausting evictions.
func (t *Table[K, V]) insert(entry Entry[K, V]) (displaced Entry[K, V], homeless bool) {
if t.tableA.update(entry.Key, entry.Value) {
func (t *Table[K, V]) insert(entry entry[K, V]) (displaced entry[K, V], homeless bool) {
if t.tableA.update(entry.key, entry.value) {
return
}
if t.tableB.update(entry.Key, entry.Value) {
if t.tableB.update(entry.key, entry.value) {
return
}
@@ -97,7 +97,7 @@ func (t *Table[K, V]) resize(capacity uint64) bool {
updated := t.resized(capacity)
for k, v := range t.Entries() {
if _, failed := updated.insert(Entry[K, V]{k, v}); failed {
if _, failed := updated.insert(entry[K, V]{k, v}); failed {
return false
}
}
@@ -153,14 +153,10 @@ func (t *Table[K, V]) Has(key K) (exists bool) {
return
}
// Put sets the value for a key. If it cannot be set, an error is returned,
// along with the last displaced entry.
//
// On failure, the returned entry and the current table contents together
// preserve all previously inserted entries and the attempted entry.
func (t *Table[K, V]) Put(key K, value V) (displaced Entry[K, V], err error) {
// Put sets the value for a key. If it cannot be set, an error is returned.
func (t *Table[K, V]) Put(key K, value V) (err error) {
var (
entry = Entry[K, V]{key, value}
entry = entry[K, V]{key, value}
homeless bool
)
@@ -173,18 +169,18 @@ func (t *Table[K, V]) Put(key K, value V) (displaced Entry[K, V], err error) {
// early when the table is sparse, while the latter catches cases where
// growing never helps.
if t.load() < t.minLoadFactor {
return entry, fmt.Errorf("bad hash: resize on load %d/%d", t.Size(), t.TotalCapacity())
return fmt.Errorf("hash functions produced a cycle at load %d/%d: %w", t.Size(), t.TotalCapacity(), ErrBadHash)
}
// It is theoretically possible to have a table with a larger capacity
// that is valid. But this chance is astronomically small, so we ignore
// it in this implementation.
if grew := t.grow(); !grew {
return entry, fmt.Errorf("bad hash: could not redistribute entries into larger table")
return fmt.Errorf("could not redistribute entries into larger table: %w", ErrBadHash)
}
}
return entry, fmt.Errorf("bad hash: could not place entry after %d resizes", defaultGrowthLimit)
return fmt.Errorf("could not place entry after %d resizes: %w", defaultGrowthLimit, ErrBadHash)
}
// Drop removes a value for a key in the table. Returns whether the key had
@@ -206,7 +202,7 @@ func (t *Table[K, V]) Entries() iter.Seq2[K, V] {
return func(yield func(K, V) bool) {
for _, slot := range t.tableA.slots {
if slot.occupied {
if !yield(slot.Key, slot.Value) {
if !yield(slot.key, slot.value) {
return
}
}
@@ -214,7 +210,7 @@ func (t *Table[K, V]) Entries() iter.Seq2[K, V] {
for _, slot := range t.tableB.slots {
if slot.occupied {
if !yield(slot.Key, slot.Value) {
if !yield(slot.key, slot.value) {
return
}
}