safemap

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2026 License: MIT Imports: 2 Imported by: 0

README

tinysafemap

tinysafemap is a lightweight, thread-safe generic map implementation designed for Go 1.23+.

It is ideal for projects that want a zero-dependency, simple Mutex-wrapped map interface without the type-casting complexity of sync.Map.

Features

  • Generics: Supports Go generics, ensuring compile-time type validation for both keys and values.
  • Atomic Updates (Update/UpdateAndGet): Provides thread-safe, functional updates to prevent race conditions during read-modify-write operations.
  • For Range Iterator Support (All()): Implements the iter.Seq2 signature, allowing clean for range loops over the concurrent map.
  • Other Features: Includes helper methods such as Len(), Has(), Clear(), and slice conversions (Keys()/Values()).
  • Zero Dependencies: Implemented purely with the Go standard library.

Usage

Basic Operations and Initialization

You can import the package using import "github.com/kohei-noda-qcrg/tinysafemap".

package main

import (
	"fmt"
	"github.com/kohei-noda-qcrg/tinysafemap"
)

func main() {
	// Initialize with default capacity
	m := safemap.NewSafeMap[string, int]()

	// Initialize with custom capacity to minimize memory allocations
	// m := safemap.NewSafeMapWithSize[string, int](100)

	// Set values
	m.Set("apple", 100)
	m.Set("banana", 200)

	// Get values
	if price, ok := m.Get("apple"); ok {
		fmt.Printf("Apple price: %d\n", price)
	}

	// Check existence
	if m.Has("banana") {
		fmt.Println("Banana exists!")
	}

	// Get size
	fmt.Printf("Total items: %d\n", m.Len()) // 2
}
Atomic Updates (Update / UpdateAndGet)

Perform atomic modifications (read-modify-write) in a single locked transaction. This is useful for concurrent counters or state updates.

// Atomically increment the value
m.Update("counter", func(v int) int {
	return v + 1
})

// Atomically update and return the new value
newVal := m.UpdateAndGet("counter", func(v int) int {
	return v * 10
})
Map Iteration

Using the All() iterator, you can iterate over the map safely using standard for range loops. A read-lock (RLock) is automatically held during the entire iteration.

[!CAUTION] Avoid modifying the map inside the loop. Since the read-lock is held during the iteration, calling any write operations (such as Set, Delete, or Update) on the same map within the loop will cause a deadlock. If you need to modify the map during iteration, collect the keys first using Keys() and iterate over that slice instead.

for key, val := range m.All() {
	fmt.Printf("%s: %d\n", key, val)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type SafeMap

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

func NewSafeMap

func NewSafeMap[K comparable, V any]() *SafeMap[K, V]

create a SafeMap instance without size (size=0)

func NewSafeMapWithSize

func NewSafeMapWithSize[K comparable, V any](size int) *SafeMap[K, V]

create a SafeMap instance with size

func (*SafeMap[K, V]) All

func (m *SafeMap[K, V]) All() iter.Seq2[K, V]

All returns a Go 1.23 compatible iterator (iter.Seq2). Note: A read-lock is held during the entire iteration. Calling write operations (e.g., Set, Delete, Update) on the same map inside the loop will cause a deadlock.

func (*SafeMap[K, V]) Clear

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

erase all elements in the safemap

func (*SafeMap[K, V]) Delete

func (m *SafeMap[K, V]) Delete(key K)

func (*SafeMap[K, V]) Get

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

func (*SafeMap[K, V]) Has

func (m *SafeMap[K, V]) Has(key K) bool

func (*SafeMap[K, V]) Keys

func (m *SafeMap[K, V]) Keys() []K

func (*SafeMap[K, V]) Len

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

func (*SafeMap[K, V]) Range

func (m *SafeMap[K, V]) Range(f func(key K, value V) bool)

func (*SafeMap[K, V]) Set

func (m *SafeMap[K, V]) Set(key K, value V)

func (*SafeMap[K, V]) Update

func (m *SafeMap[K, V]) Update(key K, f func(V) V)

func (*SafeMap[K, V]) UpdateAndGet

func (m *SafeMap[K, V]) UpdateAndGet(key K, f func(V) V) V

func (*SafeMap[K, V]) Values

func (m *SafeMap[K, V]) Values() []V

Jump to

Keyboard shortcuts

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