genmap

package module
v0.1.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 24, 2026 License: Apache-2.0 Imports: 2 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

genmap

Go Reference

Go native map only accept comparable types as key. This prominently prevents the use of slices and maps as keys.

genmap provides a generic map implementation that does not have such limitation.

Features

  • Get, Put, Remove, Upsert
  • Entry to check for a key, then update or insert its element with a single lookup
  • Len, Clear
  • Iterator allowing Remove while iterating
  • A nil map reads as empty, like a nil Go map

It's up to the user to provide a hash and an equality function for the key type (Helpers are provided for the common cases).

Limitations

The rather simple implementation is designed for the case where the number of keys is roughly known in advance. Performance will suffer if the number of keys is much larger than the number of buckets.

The number of buckets never changes. Each empty bucket still costs 24 bytes, and iterating over or clearing the map visits every bucket: with the default of 64k buckets, a map takes 1.5 MB however few keys it holds. Pass a bucket count close to the expected number of keys to NewMap.

A map is not safe for concurrent use while it is being modified.

Example usage

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)
	// prints 4
}

// Iterate over the map
it := m.Iterator()
for it.Next() {
	fmt.Printf("Key: %v, Value: %v\n", it.Cur().Key, it.Cur().Value)
}
// prints:
// Key: {1 [a b]}, Value: {4 c}
// Key: {2 [c d]}, Value: {2 b}

Benchmarks

Benchmarked against the standard map implementation. Use of a 64k bucket size for 100k keys (Apple M1 Max, Go 1.27, median of 6 runs).

BenchmarkMapGet-10                     25298931        48.96 ns/op          0 B/op        0 allocs/op
BenchmarkStdMapGet-10                  72832658        16.99 ns/op          0 B/op        0 allocs/op
BenchmarkMapPut100k-10                      241      4769061 ns/op    7720841 B/op     1440 allocs/op
BenchmarkStdMapPut100k-10                   823      1487336 ns/op    5248145 B/op      257 allocs/op
BenchmarkMapPutOverwrite-10            21949846        55.16 ns/op          0 B/op        0 allocs/op
BenchmarkStdMapPutOverwrite-10         52113963        23.29 ns/op          0 B/op        0 allocs/op
BenchmarkMapUpsert100k-10                   248      5037831 ns/op    7712815 B/op     1445 allocs/op
BenchmarkStdMapUpsert100k-10                614      1979311 ns/op    5248143 B/op      257 allocs/op
BenchmarkMapUpsertIncrement-10         21710925        58.95 ns/op          0 B/op        0 allocs/op
BenchmarkStdMapUpsertIncrement-10      33433012        37.88 ns/op          0 B/op        0 allocs/op
BenchmarkMapUpsertDelete-10            20493829        55.69 ns/op          0 B/op        0 allocs/op
BenchmarkStdMapUpsertDelete-10         31600706        39.64 ns/op          0 B/op        0 allocs/op
BenchmarkMapIterator-10                    1690       704702 ns/op          0 B/op        0 allocs/op
BenchmarkStdMapIterator-10                 2162       555166 ns/op          0 B/op        0 allocs/op

Credits

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

Examples

Constants

View Source
const (
	HashSeed uint64 = 14695981039346656037 // Seed value for the initial hash
)

Variables

This section is empty.

Functions

func CombineHash

func CombineHash(seed, hash uint64) uint64

CombineHash Combine two uint64 hashes into a single hash

func CombineHashes

func CombineHashes(hashes ...uint64) uint64

CombineHashes Combine a list of uint64 hashes into a single hash

func DeepEqual

func DeepEqual[T any](a, b T) bool

DeepEqual Deep equal comparison of two values

func Equal

func Equal[K comparable](k1, k2 K) bool

Equal Compares two `comparable` values

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]) Clear

func (m *Map[K, V]) Clear()

Clear removes all elements from the map.

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

func (m *Map[K, V]) Get(key K) (V, bool)

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]) Len

func (m *Map[K, V]) Len() int

Len returns the number of elements in 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

type MapElement[K any, V any] struct {
	Key   K
	Value V
	// contains filtered or unexported fields
}

MapElement is a generic key-value pair used in the Map[K, V] implementation.

type MapEntry added in v0.1.4

type MapEntry[K any, V any] struct {
	// contains filtered or unexported fields
}

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

type MapIterator[K any, V any] struct {
	// contains filtered or unexported fields
}

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

type MaybeMapEntry[K any, V any] struct {
	// contains filtered or unexported fields
}

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址