Documentation
¶
Overview ¶
Package genmap provides a simple generic hash map implementation that accepts keys of any type, given an equality and a hash function. This file defines the entry abstractions used to access and optionally create map elements.
The map stores its data in a slice of buckets (`[][]MapElement[K,V]`). Each bucket holds the elements whose hash maps to it (collision handling via chaining). `MapEntry` is a thin wrapper around a pointer to an existing element, while `MaybeMapEntry` represents a lookup that may or may not have found an element. The latter can be turned into a concrete entry (creating a new element if necessary) via `OrDefault`.
These helpers back `Map.Entry` and `Map.Upsert`, which update an element in place with a single lookup.
Example ¶
package main
import (
"fmt"
"github.com/ronanh/genmap"
)
type MyKey struct {
k1 int
k2 []string
}
type MyValue struct {
v1 int
v2 string
}
func NewMyKeyHasher() func(k MyKey) uint64 {
k1Hasher := genmap.NewHasher[int]()
k2Hasher := genmap.NewHasher[string]()
return func(k MyKey) uint64 {
var fieldHashes [2]uint64
fieldHashes[0] = k1Hasher(k.k1)
fieldHashes[1] = genmap.HashSeed
for _, s := range k.k2 {
fieldHashes[1] = genmap.CombineHash(fieldHashes[1], k2Hasher(s))
}
return genmap.CombineHashes(fieldHashes[:]...)
}
}
func MyKeyEquals(a, b MyKey) bool {
if a.k1 != b.k1 {
return false
}
if len(a.k2) != len(b.k2) {
return false
}
for i := range a.k2 {
if a.k2[i] != b.k2[i] {
return false
}
}
return true
}
func main() {
m := genmap.NewMap[MyKey, MyValue](MyKeyEquals, NewMyKeyHasher())
m.Put(MyKey{1, []string{"a", "b"}}, MyValue{1, "a"})
m.Put(MyKey{2, []string{"c", "d"}}, MyValue{2, "b"})
m.Put(MyKey{1, []string{"a", "b"}}, MyValue{3, "c"})
// increment the value for a key
m.Upsert(MyKey{1, []string{"a", "b"}}, func(elem *genmap.MapElement[MyKey, MyValue], exists bool) {
elem.Value.v1++
})
// Get the value for a key
if v, ok := m.Get(MyKey{1, []string{"a", "b"}}); ok {
fmt.Println(v.v1)
}
// Iterate over the map
it := m.Iterator()
for it.Next() {
fmt.Printf("Key: %v, Value: %v\n", it.Cur().Key, it.Cur().Value)
}
}
Output: 4 Key: {1 [a b]}, Value: {4 c} Key: {2 [c d]}, Value: {2 b}
Index ¶
- Constants
- func CombineHash(seed, hash uint64) uint64
- func CombineHashes(hashes ...uint64) uint64
- func DeepEqual[T any](a, b T) bool
- func Equal[K comparable](k1, k2 K) bool
- func NewHasher[T comparable]() func(T) uint64
- type Map
- func (m *Map[K, V]) Clear()
- func (m *Map[K, V]) Entry(key K) MaybeMapEntry[K, V]
- func (m *Map[K, V]) Get(key K) (V, bool)
- func (m *Map[K, V]) Iterator() *MapIterator[K, V]
- func (m *Map[K, V]) Len() int
- func (m *Map[K, V]) Put(key K, val V)
- func (m *Map[K, V]) Remove(key K) (MapElement[K, V], bool)
- func (m *Map[K, V]) Upsert(key K, update func(elem *MapElement[K, V], exists bool))
- type MapElement
- type MapEntry
- type MapIterator
- type MaybeMapEntry
Examples ¶
Constants ¶
const (
HashSeed uint64 = 14695981039346656037 // Seed value for the initial hash
)
Variables ¶
This section is empty.
Functions ¶
func CombineHash ¶
CombineHash Combine two uint64 hashes into a single hash
func CombineHashes ¶
CombineHashes Combine a list of uint64 hashes into a single hash
func NewHasher ¶
func NewHasher[T comparable]() func(T) uint64
NewHasher Returns a hash function for `comparable`
Types ¶
type Map ¶
type Map[K, V any] struct { // contains filtered or unexported fields }
Map is a generic hash map implementation that allows any type for keys. Map instance should be instantiated using the NewMap function.
func NewMap ¶
func NewMap[K any, V any](equal func(k1, k2 K) bool, hash func(k K) uint64, bucketSizeOpt ...int) *Map[K, V]
NewMap returns a new instance of Map[K, V] with the given equality and hash functions. The optional bucketSizeOpt parameter specifies the number of buckets in the map. If not provided, a default bucket size (64k) is used. Special care should be taken when choosing a bucket size as it can have a significant impact on performance. For good performance, the bucket size should be close to the expected number of elements in the map. A bucket size of 0 is treated as 1.
The map never adds buckets. Each bucket costs a slice header (24 bytes on 64-bit platforms) even when empty, and iterating over or clearing the map visits every bucket: with the default size, a map takes 1.5 MB and iterating over it scans 65,536 buckets, however few elements it holds.
func (*Map[K, V]) Entry ¶ added in v0.1.4
func (m *Map[K, V]) Entry(key K) MaybeMapEntry[K, V]
Entry returns a MaybeMapEntry that provides optional access to the element associated with the given key. The returned entry can be inspected for existence, and its element updated or inserted, without performing multiple lookups.
Example ¶
package main
import (
"fmt"
"github.com/ronanh/genmap"
)
func main() {
m := genmap.NewMap[string, int](genmap.Equal[string], genmap.NewHasher[string]())
m.Put("foo", 42)
// Look the key up once, then update its element in place.
foo := m.Entry("foo")
if foo.Exists() {
foo.OrDefault().MutateWith(func(elem *genmap.MapElement[string, int]) {
elem.Value++
})
}
// OrDefault inserts a missing key with a zero value.
bar := m.Entry("bar")
bar.OrDefault().MutateWith(func(elem *genmap.MapElement[string, int]) {
elem.Value += 10
})
fooValue, _ := m.Get("foo")
barValue, _ := m.Get("bar")
fmt.Println(fooValue, barValue, m.Len())
}
Output: 43 10 2
func (*Map[K, V]) Get ¶
Get returns the value associated with the given key, and whether the key is in the map.
func (*Map[K, V]) Iterator ¶
func (m *Map[K, V]) Iterator() *MapIterator[K, V]
Iterator returns a new iterator over the map.
func (*Map[K, V]) Put ¶
func (m *Map[K, V]) Put(key K, val V)
Put inserts the given key-value pair into the map.
func (*Map[K, V]) Remove ¶
func (m *Map[K, V]) Remove(key K) (MapElement[K, V], bool)
Remove removes the given key from the map and returns it.
func (*Map[K, V]) Upsert ¶
func (m *Map[K, V]) Upsert(key K, update func(elem *MapElement[K, V], exists bool))
Upsert inserts or modifies the given entry into the map. The update function is called with the current value or the new one.
type MapElement ¶
MapElement is a generic key-value pair used in the Map[K, V] implementation.
type MapEntry ¶ added in v0.1.4
MapEntry is a lightweight handle to an existing map element. It does not own the element; it merely holds a pointer that can be used to mutate the element via `MutateWith`.
func (MapEntry[K, V]) MutateWith ¶ added in v0.1.4
func (entry MapEntry[K, V]) MutateWith(f func(*MapElement[K, V]))
MutateWith runs the supplied function on the underlying map element. The caller can modify the key, value, or other fields directly.
type MapIterator ¶
MapIterator is an iterator over a map.
Keys added to the map during the iteration may or may not be visited. Removing keys through the map rather than through MapIterator.Remove shifts the elements of their bucket: the iterator can then skip an element, and Cur and Remove panic if its position no longer holds one.
func (*MapIterator[K, V]) Cur ¶
func (it *MapIterator[K, V]) Cur() *MapElement[K, V]
Cur returns the current element
func (*MapIterator[K, V]) Next ¶
func (it *MapIterator[K, V]) Next() bool
Next advances the iterator and returns true if there is another element
func (*MapIterator[K, V]) Remove ¶
func (it *MapIterator[K, V]) Remove() MapElement[K, V]
Remove removes the current element from the map and returns it. After calling Remove, Next must be called before calling Cur again.
func (*MapIterator[K, V]) Reset ¶
func (it *MapIterator[K, V]) Reset()
Reset resets the iterator to the beginning of the map.
type MaybeMapEntry ¶ added in v0.1.4
MaybeMapEntry represents the result of a lookup that may be absent. It stores enough context (map reference, bucket position, hash, key) to either return the found element or create a new one on demand.
func (*MaybeMapEntry[K, V]) Exists ¶ added in v0.1.4
func (entry *MaybeMapEntry[K, V]) Exists() bool
Exists reports whether the lookup succeeded (i.e. an element was found).
func (*MaybeMapEntry[K, V]) OrDefault ¶ added in v0.1.4
func (entry *MaybeMapEntry[K, V]) OrDefault() MapEntry[K, V]
OrDefault returns a concrete `MapEntry`. If the element already exists it is returned unchanged; otherwise a new element is allocated, inserted into the appropriate bucket, and a handle to that new element is returned. The entry then refers to the new element, so calling OrDefault again does not insert the key a second time.