chore: move from tools/dsa (#1)
Moved the implementation of this hash table from `tools/dsa` #1. Reviewed-on: #1 Co-authored-by: M.V. Hutz <git@maximhutz.me> Co-committed-by: M.V. Hutz <git@maximhutz.me>
This commit was merged in pull request #1.
This commit is contained in:
73
bucket.go
Normal file
73
bucket.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package cuckoo
|
||||
|
||||
type entry[K, V any] struct {
|
||||
key K
|
||||
value V
|
||||
}
|
||||
|
||||
type slot[K, V any] struct {
|
||||
entry[K, V]
|
||||
occupied bool
|
||||
}
|
||||
|
||||
type bucket[K, V any] struct {
|
||||
hash Hash[K]
|
||||
slots []slot[K, V]
|
||||
capacity, size uint64
|
||||
compare EqualFunc[K]
|
||||
}
|
||||
|
||||
func (b bucket[K, V]) location(key K) uint64 {
|
||||
return b.hash(key) % b.capacity
|
||||
}
|
||||
|
||||
func (b bucket[K, V]) get(key K) (value V, found bool) {
|
||||
slot := b.slots[b.location(key)]
|
||||
return slot.value, slot.occupied && b.compare(slot.key, key)
|
||||
}
|
||||
|
||||
func (b *bucket[K, V]) resize(capacity uint64) {
|
||||
b.slots = make([]slot[K, V], capacity)
|
||||
b.capacity = capacity
|
||||
b.size = 0
|
||||
}
|
||||
|
||||
func (b bucket[K, V]) update(key K, value V) (updated bool) {
|
||||
slot := &b.slots[b.location(key)]
|
||||
|
||||
if slot.occupied && b.compare(slot.key, key) {
|
||||
slot.value = value
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (b *bucket[K, V]) evict(insertion entry[K, V]) (evicted entry[K, V], eviction bool) {
|
||||
slot := &b.slots[b.location(insertion.key)]
|
||||
|
||||
if !slot.occupied {
|
||||
slot.entry = insertion
|
||||
slot.occupied = true
|
||||
b.size++
|
||||
return
|
||||
}
|
||||
|
||||
if b.compare(slot.key, insertion.key) {
|
||||
slot.value = insertion.value
|
||||
return
|
||||
}
|
||||
|
||||
insertion, slot.entry = slot.entry, insertion
|
||||
return insertion, true
|
||||
}
|
||||
|
||||
func newBucket[K, V any](capacity uint64, hash Hash[K], compare EqualFunc[K]) bucket[K, V] {
|
||||
return bucket[K, V]{
|
||||
hash: hash,
|
||||
capacity: capacity,
|
||||
compare: compare,
|
||||
size: 0,
|
||||
slots: make([]slot[K, V], capacity),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user