Compare commits

..

6 Commits

Author SHA1 Message Date
41b09ae680 fix: remove redundant test TestRemove (#8)
All checks were successful
CI / Makefile Lint (push) Successful in 24s
CI / Go Lint (push) Successful in 28s
CI / Markdown Lint (push) Successful in 20s
CI / Unit Tests (push) Successful in 23s
CI / Fuzz Tests (push) Successful in 54s
CI / Mutation Tests (push) Successful in 50s
This test offers the same functionality as `TestAddItem`.

Reviewed-on: #8
Co-authored-by: M.V. Hutz <git@maximhutz.me>
Co-committed-by: M.V. Hutz <git@maximhutz.me>
2026-03-21 16:24:52 +00:00
e00e6fcb1b docs: add logo for project, expand readme (#7)
All checks were successful
CI / Makefile Lint (push) Successful in 22s
CI / Go Lint (push) Successful in 26s
CI / Markdown Lint (push) Successful in 9s
CI / Unit Tests (push) Successful in 21s
CI / Fuzz Tests (push) Successful in 53s
CI / Mutation Tests (push) Successful in 1m23s
Reviewed-on: #7
Co-authored-by: M.V. Hutz <git@maximhutz.me>
Co-committed-by: M.V. Hutz <git@maximhutz.me>
2026-03-21 01:14:17 +00:00
56b1982f8a feat: add drop key functionality (#6)
All checks were successful
CI / Makefile Lint (push) Successful in 16s
CI / Go Lint (push) Successful in 21s
CI / Unit Tests (push) Successful in 15s
CI / Fuzz Tests (push) Successful in 49s
CI / Mutation Tests (push) Successful in 55s
Currently, the `Table.Drop()` function is deprecated because it is not implemented yet. Let's add that functionality.

- Adds true drop functionality to the table, through `Table.Drop()`.
- Adds tests for functionality.
- Rewrites fuzz test using `go_fuzz_utils`, to test arbitrary usage patterns.
- Rewrite `bucket` to allow a capacity of zero.
- Rename `Table.Capacity()` to `Table.TotalCapacity()`, to reflect to different between the capacity of the buckets vs. the whole table.
- Enforce 100% mutation test coverage.

Reviewed-on: #6
Co-authored-by: M.V. Hutz <git@maximhutz.me>
Co-committed-by: M.V. Hutz <git@maximhutz.me>
2026-03-20 01:59:54 +00:00
2bfaede2d4 ci: add lint makefile job (#5)
All checks were successful
CI / Makefile Lint (push) Successful in 15s
CI / Go Lint (push) Successful in 19s
CI / Unit Tests (push) Successful in 32s
CI / Fuzz Tests (push) Successful in 46s
CI / Mutation Tests (push) Successful in 51s
Currently, there is no CI job to lint the Makefile. This adds one.

Reviewed-on: #5
Co-authored-by: M.V. Hutz <git@maximhutz.me>
Co-committed-by: M.V. Hutz <git@maximhutz.me>
2026-03-19 00:24:25 +00:00
ece10585a5 style: restructure makefile (#4)
All checks were successful
CI / Unit Tests (push) Successful in 13s
CI / Go Lint (push) Successful in 17s
CI / Mutation Tests (push) Successful in 33s
CI / Fuzz Tests (push) Successful in 58s
Currently, the `Makefile` is not well structured, and does not follow best practices. With the help of [`checkmake`](https://github.com/checkmake/checkmake), the Makefile can be forced to follow them.

### Decisions

- Added CI job `lint-makefile`, which forces the Makefile to conform to standards.
- The `make help` was set as the default target. This is common practice in the industry.
- The `make help` uses `grep` | `awk` to create a command table from `##` comments after each target. It seems a bit icky, but it is something that Docker, Kubernetes, and Helm all do.

Reviewed-on: #4
Co-authored-by: M.V. Hutz <git@maximhutz.me>
Co-committed-by: M.V. Hutz <git@maximhutz.me>
2026-03-19 00:14:54 +00:00
0017a33f12 ci: clean up workflow (#3)
All checks were successful
CI / Unit Tests (push) Successful in 35s
CI / Golang Lint (push) Successful in 1m1s
CI / Fuzz Tests (push) Successful in 1m18s
CI / Mutation Tests (push) Successful in 1m12s
## Description

The current CI workflow was auto-generated by Claude, and is really not intuitive. Fixing it up to make it work better.

- Add names for jobs in workflow.
- Rename workflow to `ci.yml`.
- Added `go mod tidy` as a tasks in the `lint` job.

### Decisions

- Chose not to use emojis for workflow or job names. While they look nice, they are unprofessional, and harder to `grep`.

Reviewed-on: #3
Co-authored-by: M.V. Hutz <git@maximhutz.me>
Co-committed-by: M.V. Hutz <git@maximhutz.me>
2026-03-18 00:47:02 +00:00
16 changed files with 359 additions and 66 deletions

7
.claude/settings.json Normal file
View File

@@ -0,0 +1,7 @@
{
"permissions": {
"allow": [
"Bash(curl -s -w \"\\\\n---HTTP_STATUS:%{http_code}---\" https://raw.githubusercontent.com/kubernetes/kubernetes/master/.markdownlint.yaml)"
]
}
}

View File

@@ -1,16 +1,13 @@
name: CI name: CI
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on: on:
push: push:
branches: [main] branches: [main]
pull_request: pull_request:
jobs: jobs:
lint: lint-go:
name: Go Lint
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -19,11 +16,39 @@ jobs:
with: with:
go-version-file: go.mod go-version-file: go.mod
- name: Check go mod tidy
run: go mod tidy && git diff --exit-code go.mod go.sum
- uses: golangci/golangci-lint-action@v7 - uses: golangci/golangci-lint-action@v7
with: with:
version: latest version: latest
unit-test: lint-makefile:
name: Makefile Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Install gremlins
run: go install github.com/checkmake/checkmake/cmd/checkmake@latest
- name: Run mutation tests
run: make lint-makefile
lint-markdown:
name: Markdown Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: DavidAnson/markdownlint-cli2-action@v19
test-unit:
name: Unit Tests
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -33,9 +58,10 @@ jobs:
go-version-file: go.mod go-version-file: go.mod
- name: Run unit tests - name: Run unit tests
run: go test ./... -cover -v run: make test-unit
fuzz-test: test-fuzz:
name: Fuzz Tests
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -45,12 +71,10 @@ jobs:
go-version-file: go.mod go-version-file: go.mod
- name: Run fuzz tests - name: Run fuzz tests
run: | run: make test-fuzz
for func in $(grep -r --include='*_test.go' -oh 'func Fuzz\w*' . | sed 's/func //'); do
go test ./... -fuzz="^${func}$" -fuzztime=30s
done
mutation-test: test-mutation:
name: Mutation Tests
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -63,4 +87,4 @@ jobs:
run: go install github.com/go-gremlins/gremlins/cmd/gremlins@latest run: go install github.com/go-gremlins/gremlins/cmd/gremlins@latest
- name: Run mutation tests - name: Run mutation tests
run: gremlins unleash run: make test-mutation

View File

@@ -4,4 +4,6 @@ unleash:
timeout-coefficient: 50 timeout-coefficient: 50
workers: 4 workers: 4
dry-run: false dry-run: false
threshold:
efficacy: 1.0

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,12 +1,47 @@
unit: .PHONY: all help install clean test-unit test-mutation test-fuzz test docs lint-go lint-makefile lint-markdown lint
help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*##' $(MAKEFILE_LIST) | awk -F ':.*## ' '{printf " %-15s %s\n", $$1, $$2}'
install: ## Install dev tools
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
go install github.com/checkmake/checkmake/cmd/checkmake@latest
go install github.com/go-gremlins/gremlins/cmd/gremlins@latest
go install golang.org/x/tools/cmd/godoc@latest
go install golang.org/x/vuln/cmd/govulncheck@latest
test-unit: ## Run unit tests with coverage
go test ./... -cover -v go test ./... -cover -v
mutation: test-mutation: ## Run mutation tests with gremlins
gremlins unleash gremlins unleash
fuzz: FUZZ_TIME ?= 30
go test ./... -fuzz=$(FN)
docs: test-fuzz: ## Run all fuzz tests for 30s each
@echo ">>> Visit: http://localhost:6060/pkg/git.maximhutz.com/tools/dsa/" @for func in $$(grep -r --include='*_test.go' -oh 'func Fuzz\w*' . | sed 's/func //'); do \
godoc -http=:6060 echo "Fuzzing $$func..."; \
go test ./... -fuzz="^$$func$$" -fuzztime=$(FUZZ_TIME)s; \
done
test: test-unit test-mutation test-fuzz ## Run all tests
lint-go: ## Lint Go code
golangci-lint run ./...
lint-makefile: ## Lint the Makefile
checkmake Makefile
lint-markdown: ## Lint Markdown files
docker run --rm -v $(CURDIR):/workdir davidanson/markdownlint-cli2 "**/*.md"
lint: lint-go lint-makefile lint-markdown ## Lint all code
docs: ## Serve godoc locally
@echo ">>> Visit: http://localhost:6060/pkg/$$(go list -m)"
godoc -http=:6060
clean: ## Clean build and test caches
go clean -cache -testcache
all: lint test ## Run all checks and tests

View File

@@ -1,3 +1,3 @@
# 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).

1
assets/logo.svg Normal file
View File

@@ -0,0 +1 @@
<svg width="16" height="16" xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges"><path fill="#2a1512" d="M3,6h1v1h-1v-1M2,7h1v1h-1v-1M12,7h1v1h-1v-1M1,8h1v1h-1v-1M4,8h1v2h-1v-2M14,8h1v1h-1v-1M11,9h1v2h-2v-1h1v-1M5,10h1v1h-1v-1M1,13h2v1h1v1h-2v-1h-1v-1M13,13h2v1h-1v1h-1v1h-1v-2h1v-1M4,15h1v1h-1v-1"/><path fill="#38231f" d="M4,6h1v1h-1v-1M11,6h1v1h-1v-1M13,7h1v1h-1v-1M1,9h1v2h-1v-2M14,9h1v1h-1v-1M14,11h1v2h-1v-2M1,12h1v1h-1v-1M5,15h3v1h-3v-1M10,15h2v1h-2v-1"/><path fill="#3f3f74" d="M7,3h2v1h-2v-1M6,4h1v1h-1v-1M9,4h1v1h-1v-1M5,5h1v5h-1v-5M10,5h1v5h-1v-5M6,10h4v1h-4v-1"/><path fill="#6262ab" d="M9,5h1v1h-1v-1M6,9h1v1h-1v-1M9,9h1v1h-1v-1"/><path fill="#663931" d="M11,8h1v1h-1v-1M2,9h1v1h-1v-1M14,10h1v1h-1v-1M1,11h1v1h-1v-1M3,11h2v1h-2v-1M13,11h1v1h-1v-1M2,12h1v1h-1v-1M5,12h1v1h-1v-1M10,12h3v2h-1v-1h-2v-1M3,13h1v1h-1v-1M8,13h2v1h-2v-1M4,14h3v1h-3v-1M10,14h2v1h-2v-1M8,15h2v1h-2v-1"/><path fill="#8d8dcb" d="M9,6h1v3h-1v1h-2v-1h1v-1h1v-2M6,8h1v1h-1v-1"/><path fill="#8f563b" d="M2,8h1v1h-1v-1M12,9h1v1h-1v-1M2,10h1v1h-1v-1M13,10h1v1h-1v-1M7,11h1v1h-1v-1M11,11h2v1h-2v-1M4,12h1v1h1v-1h1v2h-3v-2M13,12h1v1h-1v-1M10,13h2v1h-2v-1M7,14h3v1h-3v-1"/><path fill="#a4a4d5" d="M8,4h1v4h-1v1h-1v-1h-1v-2h1v-1h1v-1"/><path fill="#ab764a" d="M4,7h1v1h-1v-1M3,8h1v2h-1v-2M12,10h1v1h-1v-1M2,11h1v1h-1v-1M8,11h1v1h-1v-1M3,12h1v1h-1v-1M7,12h1v2h-1v-2"/><path fill="#cacaea" d="M7,4h1v1h-1v-1M6,5h1v1h-1v-1"/><path fill="#d9a066" d="M3,7h1v1h-1v-1M11,7h1v1h-1v-1M12,8h2v2h-1v-1h-1v-1M3,10h2v1h-2v-1M5,11h2v1h-2v-1M9,11h2v1h-1v1h-2v-1h1v-1"/></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
assets/logo128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 963 B

BIN
assets/logo16x16.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 418 B

View File

@@ -17,15 +17,37 @@ type bucket[K, V any] struct {
compare EqualFunc[K] 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 bucket[K, V]) location(key K) uint64 { func (b bucket[K, V]) location(key K) uint64 {
return b.hash(key) % b.capacity return b.hash(key) % b.capacity
} }
func (b bucket[K, V]) get(key K) (value V, found bool) { func (b bucket[K, V]) get(key K) (value V, found bool) {
if b.capacity == 0 {
return
}
slot := b.slots[b.location(key)] slot := b.slots[b.location(key)]
return slot.value, slot.occupied && b.compare(slot.key, key) return slot.value, slot.occupied && b.compare(slot.key, key)
} }
func (b *bucket[K, V]) drop(key K) (occupied bool) {
if b.capacity == 0 {
return
}
slot := &b.slots[b.location(key)]
if slot.occupied && b.compare(slot.key, key) {
slot.occupied = false
b.size--
return true
}
return false
}
func (b *bucket[K, V]) resize(capacity uint64) { func (b *bucket[K, V]) resize(capacity uint64) {
b.slots = make([]slot[K, V], capacity) b.slots = make([]slot[K, V], capacity)
b.capacity = capacity b.capacity = capacity
@@ -33,6 +55,10 @@ func (b *bucket[K, V]) resize(capacity uint64) {
} }
func (b bucket[K, V]) update(key K, value V) (updated bool) { func (b bucket[K, V]) update(key K, value V) (updated bool) {
if b.capacity == 0 {
return
}
slot := &b.slots[b.location(key)] slot := &b.slots[b.location(key)]
if slot.occupied && b.compare(slot.key, key) { if slot.occupied && b.compare(slot.key, key) {
@@ -44,6 +70,10 @@ func (b bucket[K, V]) update(key K, value V) (updated bool) {
} }
func (b *bucket[K, V]) evict(insertion entry[K, V]) (evicted entry[K, V], eviction bool) { func (b *bucket[K, V]) evict(insertion entry[K, V]) (evicted entry[K, V], eviction bool) {
if b.capacity == 0 {
return insertion, true
}
slot := &b.slots[b.location(insertion.key)] slot := &b.slots[b.location(insertion.key)]
if !slot.occupied { if !slot.occupied {

View File

@@ -1,11 +1,11 @@
package cuckoo_test package cuckoo_test
import ( import (
"bytes" "maps"
"encoding/binary"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
go_fuzz_utils "github.com/trailofbits/go-fuzz-utils"
"git.maximhutz.com/tools/go-cuckoo" "git.maximhutz.com/tools/go-cuckoo"
) )
@@ -19,31 +19,60 @@ func offsetHash(seed uint32) cuckoo.Hash[uint32] {
} }
} }
type fuzzStep struct {
drop bool
key, value uint32
}
type fuzzScenario struct {
seedA, seedB uint32
steps []fuzzStep
}
func FuzzInsertLookup(f *testing.F) { func FuzzInsertLookup(f *testing.F) {
f.Fuzz(func(t *testing.T, data []byte, seedA, seedB uint32) { f.Fuzz(func(t *testing.T, data []byte) {
var scenario fuzzScenario
assert := assert.New(t) assert := assert.New(t)
table := cuckoo.NewCustomTable[uint32, uint32]( if tp, err := go_fuzz_utils.NewTypeProvider(data); err != nil {
offsetHash(seedA), return
offsetHash(seedB), } else if err := tp.Fill(&scenario); err != nil {
func(a, b uint32) bool { return a == b },
)
if seedA == seedB {
return return
} }
r := bytes.NewReader(data) if scenario.seedA == scenario.seedB {
var key, value uint32 return
for binary.Read(r, binary.LittleEndian, &key) == nil && }
binary.Read(r, binary.LittleEndian, &value) == nil {
err := table.Put(key, value) actual := cuckoo.NewCustomTable[uint32, uint32](
assert.NoError(err) offsetHash(scenario.seedA),
offsetHash(scenario.seedB),
func(a, b uint32) bool { return a == b },
)
found, err := table.Get(key) expected := map[uint32]uint32{}
assert.NoError(err)
assert.Equal(value, found) for _, step := range scenario.steps {
if step.drop {
err := actual.Drop(step.key)
assert.NoError(err)
delete(expected, step.key)
_, err = actual.Get(step.key)
assert.Error(err)
} else {
err := actual.Put(step.key, step.value)
assert.NoError(err)
expected[step.key] = step.value
found, err := actual.Get(step.key)
assert.NoError(err)
assert.Equal(step.value, found)
}
assert.Equal(expected, maps.Collect(actual.Entries()))
} }
}) })
} }

View File

@@ -25,6 +25,6 @@ func TestLoad(t *testing.T) {
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.Capacity()), table.load()) assert.Equal(float64(table.Size())/float64(table.TotalCapacity()), table.load())
} }
} }

View File

@@ -1,6 +1,7 @@
package cuckoo_test package cuckoo_test
import ( import (
"errors"
"maps" "maps"
"math/rand/v2" "math/rand/v2"
"testing" "testing"
@@ -64,7 +65,7 @@ func TestStartingCapacity(t *testing.T) {
assert := assert.New(t) assert := assert.New(t)
table := cuckoo.NewTable[int, bool](cuckoo.Capacity(64)) table := cuckoo.NewTable[int, bool](cuckoo.Capacity(64))
assert.Equal(uint64(128), table.Capacity()) assert.Equal(uint64(128), table.TotalCapacity())
} }
func TestResizeCapacity(t *testing.T) { func TestResizeCapacity(t *testing.T) {
@@ -74,12 +75,12 @@ func TestResizeCapacity(t *testing.T) {
cuckoo.GrowthFactor(2), cuckoo.GrowthFactor(2),
) )
for table.Capacity() == 16 { for table.TotalCapacity() == 16 {
err := table.Put(rand.Int(), true) err := table.Put(rand.Int(), true)
assert.NoError(err) assert.NoError(err)
} }
assert.Equal(uint64(32), table.Capacity()) assert.Equal(uint64(32), table.TotalCapacity())
} }
func TestPutMany(t *testing.T) { func TestPutMany(t *testing.T) {
@@ -117,14 +118,112 @@ func TestGetMany(t *testing.T) {
} }
} }
func TestRemove(t *testing.T) { func TestDropExistingItem(t *testing.T) {
assert := assert.New(t) assert := assert.New(t)
key, value := 0, true
table := cuckoo.NewTable[int, bool]()
(table.Put(key, value))
err := table.Drop(key)
assert.NoError(err)
assert.Equal(0, table.Size())
assert.False(table.Has(key))
}
func TestDropNoItem(t *testing.T) {
assert := assert.New(t)
key := 0
table := cuckoo.NewTable[int, bool]() table := cuckoo.NewTable[int, bool]()
assert.False(table.Has(0)) err := table.Drop(key)
err := table.Put(0, true)
assert.NoError(err) assert.NoError(err)
assert.Equal(0, table.Size())
assert.True(table.Has(0)) assert.False(table.Has(key))
}
func TestDropItemCapacity(t *testing.T) {
assert := assert.New(t)
key := 0
table := cuckoo.NewTable[int, bool](
cuckoo.Capacity(64),
cuckoo.GrowthFactor(2),
)
startingCapacity := table.TotalCapacity()
err := table.Drop(key)
endingCapacity := table.TotalCapacity()
assert.NoError(err)
assert.Equal(0, table.Size())
assert.Equal(uint64(128), startingCapacity)
assert.Equal(uint64(64), endingCapacity)
}
func TestPutNoCapacity(t *testing.T) {
assert := assert.New(t)
key, value := 0, true
table := cuckoo.NewTable[int, bool](
cuckoo.Capacity(0),
)
err := table.Put(key, value)
assert.NoError(err)
assert.Equal(1, table.Size())
assert.True(table.Has(key))
}
func TestBadHashCapacity(t *testing.T) {
assert := assert.New(t)
table := cuckoo.NewCustomTable[int, bool](
func(int) uint64 { return 0 },
func(int) uint64 { return 0 },
func(a, b int) bool { return a == b },
cuckoo.Capacity(20),
)
err1 := table.Put(0, true)
err2 := table.Put(1, true)
err3 := table.Put(2, true)
assert.NoError(err1)
assert.NoError(err2)
assert.Error(err3)
assert.Equal(uint64(80), table.TotalCapacity())
}
func TestDropResizeCapacity(t *testing.T) {
assert := assert.New(t)
table := cuckoo.NewTable[int, bool](
cuckoo.Capacity(10),
)
err1 := table.Put(0, true)
err2 := table.Put(1, true)
err3 := table.Drop(1)
assert.NoError(errors.Join(err1, err2, err3))
assert.Equal(uint64(20), table.TotalCapacity())
}
func TestNewTableBy(t *testing.T) {
type User struct {
_ func()
id string
name string
}
assert := assert.New(t)
table := cuckoo.NewTableBy[User, bool](
func(u User) string { return u.id },
)
err := table.Put(User{nil, "1", "Robert"}, true)
assert.NoError(err)
assert.Equal(1, table.Size())
assert.True(table.Has(User{nil, "1", "Robbie"}))
} }

3
go.mod
View File

@@ -4,8 +4,11 @@ go 1.25.6
require github.com/stretchr/testify v1.11.1 require github.com/stretchr/testify v1.11.1
require github.com/kr/pretty v0.3.1 // indirect
require ( require (
github.com/davecgh/go-spew v1.1.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/trailofbits/go-fuzz-utils v0.0.0-20260318143407-0907cafe7589
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

12
go.sum
View File

@@ -1,9 +1,21 @@
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/trailofbits/go-fuzz-utils v0.0.0-20260318143407-0907cafe7589 h1:UmBZCTPdDYore2IEHN+U4eIqEaRq6METh9pKiPumkqc=
github.com/trailofbits/go-fuzz-utils v0.0.0-20260318143407-0907cafe7589/go.mod h1:zh+T+w9XT/3o4E0WLEGCdmLJ8Yqx/zY3o538tQY3OjY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -16,9 +16,9 @@ type Table[K, V any] struct {
minLoadFactor float64 minLoadFactor float64
} }
// Capacity returns the number of slots allocated for the [Table]. To get the // TotalCapacity returns the number of slots allocated for the [Table]. To get the
// number of slots filled, look at [Table.Size]. // number of slots filled, look at [Table.Size].
func (t Table[K, V]) Capacity() uint64 { func (t Table[K, V]) TotalCapacity() uint64 {
return t.bucketA.capacity + t.bucketB.capacity return t.bucketA.capacity + t.bucketB.capacity
} }
@@ -28,25 +28,34 @@ func (t Table[K, V]) Size() int {
} }
func log2(n uint64) (m int) { func log2(n uint64) (m int) {
return bits.Len64(n) - 1 return max(0, bits.Len64(n)-1)
} }
func (t Table[K, V]) maxEvictions() int { func (t Table[K, V]) maxEvictions() int {
return 3 * log2(t.Capacity()) return 3 * log2(t.TotalCapacity())
} }
func (t Table[K, V]) load() float64 { func (t Table[K, V]) load() float64 {
return float64(t.Size()) / float64(t.Capacity()) // When there are no slots in the table, we still treat the load as 100%.
// Every slot in the table is full.
if t.TotalCapacity() == 0 {
return 1.0
}
return float64(t.Size()) / float64(t.TotalCapacity())
} }
func (t *Table[K, V]) resize() error { // resize clears all buckets, changes the sizes of them to a specific capacity,
// and fills them back up again. It is a helper function for [Table.grow] and
// [Table.shrink]; use them instead.
func (t *Table[K, V]) resize(capacity uint64) error {
entries := make([]entry[K, V], 0, t.Size()) entries := make([]entry[K, V], 0, t.Size())
for k, v := range t.Entries() { for k, v := range t.Entries() {
entries = append(entries, entry[K, V]{k, v}) entries = append(entries, entry[K, V]{k, v})
} }
t.bucketA.resize(t.growthFactor * t.bucketA.capacity) t.bucketA.resize(capacity)
t.bucketB.resize(t.growthFactor * t.bucketB.capacity) t.bucketB.resize(capacity)
for _, entry := range entries { for _, entry := range entries {
if err := t.Put(entry.key, entry.value); err != nil { if err := t.Put(entry.key, entry.value); err != nil {
@@ -57,6 +66,26 @@ func (t *Table[K, V]) resize() error {
return nil return nil
} }
// grow increases the table's capacity by the [Table.growthFactor]. If the
// capacity is 0, it increases it to 1.
func (t *Table[K, V]) grow() error {
var newCapacity uint64
if t.TotalCapacity() == 0 {
newCapacity = 1
} else {
newCapacity = t.bucketA.capacity * t.growthFactor
}
return t.resize(newCapacity)
}
// shrink reduces the table's capacity by the [Table.growthFactor]. It may
// reduce it down to 0.
func (t *Table[K, V]) shrink() error {
return t.resize(t.bucketA.capacity / t.growthFactor)
}
// Get fetches the value for a key in the [Table]. Returns an error if no value // Get fetches the value for a key in the [Table]. Returns an error if no value
// is found. // is found.
func (t Table[K, V]) Get(key K) (value V, err error) { func (t Table[K, V]) Get(key K) (value V, err error) {
@@ -99,10 +128,10 @@ func (t *Table[K, V]) Put(key K, value V) (err error) {
} }
if t.load() < t.minLoadFactor { if t.load() < t.minLoadFactor {
return fmt.Errorf("bad hash: resize on load %d/%d = %f", t.Size(), t.Capacity(), t.load()) return fmt.Errorf("bad hash: resize on load %d/%d = %f", t.Size(), t.TotalCapacity(), t.load())
} }
if err := t.resize(); err != nil { if err := t.grow(); err != nil {
return err return err
} }
@@ -111,10 +140,15 @@ func (t *Table[K, V]) Put(key K, value V) (err error) {
// Drop removes a value for a key in the table. Returns an error if its value // Drop removes a value for a key in the table. Returns an error if its value
// cannot be removed. // cannot be removed.
// func (t *Table[K, V]) Drop(key K) (err error) {
// Deprecated: Do not use. t.bucketA.drop(key)
func (t Table[K, V]) Drop(_ K) { t.bucketB.drop(key)
panic("Not implemented")
if t.load() < t.minLoadFactor {
return t.shrink()
}
return nil
} }
// Entries returns an unordered sequence of all key-value pairs in the table. // Entries returns an unordered sequence of all key-value pairs in the table.