safemap

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: Apache-2.0, MIT Imports: 8 Imported by: 3

README

SafeMap

SafeMap is a thread-safe map in Go with additional features, such as ordered keys and more.

Installation

To install the package, use the following command:

go install github.com/hitsumitomo/safemap@latest
Methods
  • New[K cmp.Ordered, V any](ordered ...bool) *M[K, V]: Initialize a new SafeMap. If safemap.Ordered is provided, keys will maintain insertion order.
  • Exists(key K) (exists bool): Check if a key exists in the map.
  • Load(key K) (value V, ok bool): Retrieves the value associated with a key.
  • Store(key K, value V): Store a key-value pair in the map.
  • Delete(key K): Removes a key from the map.
  • Add(key K, value V): Adds a value to the existing value for the given key.
  • Sub(key K, value V): Subtracts a value from the existing value for the given key.
  • LoadAndDelete(key K) (value V, ok bool): Load and delete a key from the map.
  • LoadOrStore(key K, value V) (actual V, loaded bool): Load or store a key-value pair in the map.
  • Swap(key K, value V) (previous V, loaded bool): Swap the value for a key and return the previous value.
  • Range(f func(K, V) bool): Iterate over the map with a function.
  • RangeDelete(f func(K, V) int8): Iterate over the map and delete keys based on a function that returns: -1 to delete the key, 0 to break the loop, and 1 to continue iterating.
  • Clear(): Clear all entries in the map.
  • Len() int: Returns the number of entries in the map.
  • Keys() []K: Returns a slice of all keys in the map.
  • Map() map[K]V: Returns a clone of the underlying map.
  • KeysInRange(from, to K) []K: Returns all keys within the specified range [from, to). Note: only works for positive numbers.

Basic example

package main

import (
	"fmt"

	"github.com/hitsumitomo/safemap"
)

func main() {
	sm := safemap.New[int, string]() // *safemap.M

	sm.Store(1, "one")
	sm.Store(2, "two")
	sm.Store(3, "three")

	if value, ok := sm.Load(2); ok {
		fmt.Println("Loaded value:", value)
	}

	if sm.Exists(3) {
		fmt.Println("Key 3 exists")
	}

	sm.Delete(1)

	sm.Range(func(key int, value string) bool {
		fmt.Printf("Key: %d, Value: %s\n", key, value)
		return true
	})

	fmt.Println("Length of map:", sm.Len())

	fmt.Println("\nUpdated map:")
	sm.Range(func(key int, value string) bool {
		fmt.Printf("Key: %d, Value: %s\n", key, value)
		return true
	})

	sm.RangeDelete(func(key int, value string) int8 {
		if key == 2 {
			return -1
		}
		return 1
	})

	fmt.Println("\nUpdated map:")
	sm.Range(func(key int, value string) bool {
		fmt.Printf("Key: %d, Value: %s\n", key, value)
		return true
	})

	sm.Clear()
	fmt.Println("Map cleared, length:", sm.Len())

	// ordered in the order of insertion.
	sm = safemap.New[int, string](safemap.Ordered)
	sm.Store(1, "Efficient")
	sm.Store(5, "solutions")
	sm.Store(2, "for")
	sm.Store(4, "complex")
	sm.Store(3, "tasks")
	fmt.Printf("\nOrdered map\n")
	sm.Range(func(key int, value string) bool {
		fmt.Printf("Key: %d, Value: %s\n", key, value)
		return true
	})
}

// Loaded value: two
// Key 3 exists
// Key: 2, Value: two
// Key: 3, Value: three
// Length of map: 2
//
// Updated map:
// Key: 2, Value: two
// Key: 3, Value: three
//
// Updated map:
// Key: 3, Value: three
// Map cleared, length: 0
//
// Ordered map
// Key: 1, Value: Efficient
// Key: 5, Value: solutions
// Key: 2, Value: for
// Key: 4, Value: complex
// Key: 3, Value: tasks
Benchmarks
BenchmarkSafeMap_Store-4                 1000000    1053 ns/op        265 B/op     2 allocs/op
BenchmarkSafeMap_Load-4                 48625240      24.63 ns/op       0 B/op     0 allocs/op
BenchmarkSafeMap_Delete-4                4250373     282.5 ns/op       55 B/op     1 allocs/op

BenchmarkSafeMap_Ordered_Store-4         1000000    1038 ns/op        265 B/op     2 allocs/op
BenchmarkSafeMap_Ordered_Load-4         48494152      24.65 ns/op       0 B/op     0 allocs/op
BenchmarkSafeMap_Ordered_Delete-4        4291180     276.9 ns/op       55 B/op     1 allocs/op

BenchmarkSyncMap_Store-4                 1000000    1001 ns/op        171 B/op     4 allocs/op
BenchmarkSyncMap_Load-4                 38536724      31.13 ns/op       0 B/op     0 allocs/op
BenchmarkSyncMap_Delete-4                1652521     728.0 ns/op      335 B/op     7 allocs/op

Documentation

Index

Constants

View Source
const Ordered = true

Variables

This section is empty.

Functions

This section is empty.

Types

type M

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

func New

func New[K comparable, V any](ordered ...bool) (m *M[K, V])

func NewOrdered

func NewOrdered[K comparable, V any](yield iter.Seq2[K, V]) (m *M[K, V])

func NewStringer

func NewStringer(ordered ...bool) (m *M[string, string])

func NewStringerKeys

func NewStringerKeys(keys []string, ordered ...bool) (m *M[string, string])

func (*M[K, V]) Collect

func (s *M[K, V]) Collect(seq iter.Seq2[K, V]) *M[K, V]

func (*M[K, V]) CopyFromMap

func (s *M[K, V]) CopyFromMap(data map[K]V)

func (*M[K, V]) Delete

func (s *M[K, V]) Delete(key K)

func (*M[K, V]) Empty

func (s *M[K, V]) Empty() bool

func (*M[K, V]) Get

func (s *M[K, V]) Get(key K) (value V, exist bool)

func (*M[K, V]) GetAndDelete

func (s *M[K, V]) GetAndDelete(key K) (value V, exist bool)

func (*M[K, V]) GetMust

func (s *M[K, V]) GetMust(key K) (value V)

func (*M[K, V]) GetMustCallback

func (s *M[K, V]) GetMustCallback(key K, callback func(value V) V) (value V)

func (*M[K, V]) Has

func (s *M[K, V]) Has(key K) (exists bool)

func (*M[K, V]) Keys

func (s *M[K, V]) Keys() []K

func (*M[K, V]) LastKey

func (s *M[K, V]) LastKey() K

func (*M[K, V]) LastValue

func (s *M[K, V]) LastValue() V

func (*M[K, V]) Len

func (s *M[K, V]) Len() int

func (*M[K, V]) Lock

func (s *M[K, V]) Lock()

func (*M[K, V]) Map

func (s *M[K, V]) Map() map[K]V

func (*M[K, V]) MarshalJSON

func (s *M[K, V]) MarshalJSON() (data []byte, err error)

func (*M[K, V]) RLock

func (s *M[K, V]) RLock()

func (*M[K, V]) RUnlock

func (s *M[K, V]) RUnlock()

func (*M[K, V]) Range

func (s *M[K, V]) Range() iter.Seq2[K, V]

func (*M[K, V]) RangeKeys

func (s *M[K, V]) RangeKeys() iter.Seq[K]

func (*M[K, V]) Remove

func (s *M[K, V]) Remove(key K)

func (*M[K, V]) Reset

func (s *M[K, V]) Reset()

func (*M[K, V]) Set

func (s *M[K, V]) Set(key K, value V) (actual V, exist bool)

func (*M[K, V]) String

func (s *M[K, V]) String() string

func (*M[K, V]) Unlock

func (s *M[K, V]) Unlock()

func (*M[K, V]) UnmarshalJSON

func (s *M[K, V]) UnmarshalJSON(data []byte) (err error)

func (*M[K, V]) Update

func (s *M[K, V]) Update(key K, value V)

func (*M[K, V]) Values

func (s *M[K, V]) Values() []V

Jump to

Keyboard shortcuts

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