4 Commits

Author SHA1 Message Date
1f7c64366d Merge remote-tracking branch 'origin' into feat/safe-put
Some checks failed
CI / Check PR Title (pull_request) Successful in 31s
CI / Go Lint (pull_request) Successful in 52s
CI / Markdown Lint (pull_request) Successful in 34s
CI / Makefile Lint (pull_request) Successful in 50s
CI / Unit Tests (pull_request) Successful in 48s
CI / Fuzz Tests (pull_request) Failing after 41s
CI / Mutation Tests (pull_request) Successful in 1m3s
2026-04-15 23:59:23 -04:00
ca66ccd040 fix: public facing key/value fields in entry
All checks were successful
CI / Check PR Title (pull_request) Successful in 19s
CI / Go Lint (pull_request) Successful in 42s
CI / Markdown Lint (pull_request) Successful in 23s
CI / Makefile Lint (pull_request) Successful in 41s
CI / Unit Tests (pull_request) Successful in 41s
CI / Fuzz Tests (pull_request) Successful in 1m12s
CI / Mutation Tests (pull_request) Successful in 58s
2026-04-04 00:38:27 +02:00
afead3330a feat: drop item returns bool, whether item existed 2026-04-04 00:20:34 +02:00
05b633afca feat: new put implementation 2026-04-04 00:13:50 +02:00
11 changed files with 88 additions and 135 deletions

View File

@@ -1,14 +0,0 @@
{
"customRules": [".markdownlint-rules/one-sentence-per-line.mjs"],
"config": {
"default": true,
"heading-style": { "style": "atx" },
"ul-indent": { "indent": 2 },
"line-length": false,
"no-duplicate-heading": { "siblings_only": true },
"no-inline-html": {
"allowed_elements": ["br", "code", "details", "summary", "img", "picture", "source"]
},
"first-line-heading": true
}
}

View File

@@ -1,48 +0,0 @@
// @ts-check
/**
* @typedef {object} ErrorInfo
* @property {number} lineNumber
* @property {string} [context]
* @property {string} [detail]
* @property {[number, number]} [range]
*/
/**
* @typedef {object} Params
* @property {string[]} lines
*/
/** @typedef {(error: ErrorInfo) => void} OnError */
/**
* @typedef {object} Rule
* @property {string[]} names
* @property {string} description
* @property {string[]} tags
* @property {(params: Params, onError: OnError) => void} function
*/
/** @type {Rule} */
export default {
names: ["one-sentence-per-line"],
description: "Each sentence must be on its own line",
tags: ["sentences"],
function: function (params, onError) {
let inFence = false;
params.lines.forEach((line, index) => {
if (/^```/.test(line)) {
inFence = !inFence;
return;
}
if (inFence) return;
// Skip headings, blank lines, HTML, table rows
if (/^(#|\s*[|<]|>|\s*$)/.test(line)) return;
// Strip list marker before checking
const text = line.replace(/^\s*(?:[-*+]|\d+\.)\s+/, "");
if (/[.!?]\s+[A-Z]/.test(text)) {
onError({ lineNumber: index + 1, context: text.trim() });
}
});
},
};

17
.markdownlint.yml Normal file
View File

@@ -0,0 +1,17 @@
default: true
heading-style:
style: atx
ul-indent:
indent: 2
line-length: false
no-duplicate-heading:
siblings_only: true
no-inline-html:
allowed_elements:
- br
- details
- summary
- img
- picture
- source
first-line-heading: true

View File

@@ -1,6 +1,3 @@
# <img height="30" src="assets/logo.svg" alt="Go Cuckoo, by `mvhutz`."> Go Cuckoo # <img height="30" src="assets/logo.svg" alt="Go Cuckoo, by `mvhutz`."> Go Cuckoo
A hash table that uses cuckoo hashing to achieve a worst-case O(1) lookup time. A hash table that uses cuckoo hashing to achieve a worst-case O(1) lookup time. Read more about it in [the package documentation](https://pkg.go.dev/git.maximhutz.com/tools/go-cuckoo).
Read more about it in [the package documentation][docs].
[docs]: https://pkg.go.dev/git.maximhutz.com/tools/go-cuckoo

View File

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

View File

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

3
doc.go
View File

@@ -5,8 +5,5 @@
// a table with any key type using [NewCustom]. Custom [Hash] functions and // a table with any key type using [NewCustom]. Custom [Hash] functions and
// key comparison are also supported. // 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 // See more: https://en.wikipedia.org/wiki/Cuckoo_hashing
package cuckoo package cuckoo

View File

@@ -10,7 +10,7 @@ import (
func Example_basic() { func Example_basic() {
table := cuckoo.New[int, string]() 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) fmt.Println("Put error:", err)
} }

View File

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

View File

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