1package csync
2
3import (
4 "encoding/json"
5 "iter"
6 "maps"
7 "sync"
8)
9
10// Map is a concurrent map implementation that provides thread-safe access.
11type Map[K comparable, V any] struct {
12 inner map[K]V
13 mu sync.RWMutex
14}
15
16// NewMap creates a new thread-safe map with the specified key and value types.
17func NewMap[K comparable, V any]() *Map[K, V] {
18 return &Map[K, V]{
19 inner: make(map[K]V),
20 }
21}
22
23// NewMapFrom creates a new thread-safe map from an existing map.
24func NewMapFrom[K comparable, V any](m map[K]V) *Map[K, V] {
25 return &Map[K, V]{
26 inner: m,
27 }
28}
29
30// Set sets the value for the specified key in the map.
31func (m *Map[K, V]) Set(key K, value V) {
32 m.mu.Lock()
33 defer m.mu.Unlock()
34 m.inner[key] = value
35}
36
37// Del deletes the specified key from the map.
38func (m *Map[K, V]) Del(key K) {
39 m.mu.Lock()
40 defer m.mu.Unlock()
41 delete(m.inner, key)
42}
43
44// Get gets the value for the specified key from the map.
45func (m *Map[K, V]) Get(key K) (V, bool) {
46 m.mu.RLock()
47 defer m.mu.RUnlock()
48 v, ok := m.inner[key]
49 return v, ok
50}
51
52// Len returns the number of items in the map.
53func (m *Map[K, V]) Len() int {
54 m.mu.RLock()
55 defer m.mu.RUnlock()
56 return len(m.inner)
57}
58
59// Seq2 returns an iter.Seq2 that yields key-value pairs from the map.
60func (m *Map[K, V]) Seq2() iter.Seq2[K, V] {
61 dst := make(map[K]V)
62 m.mu.RLock()
63 maps.Copy(dst, m.inner)
64 m.mu.RUnlock()
65 return func(yield func(K, V) bool) {
66 for k, v := range dst {
67 if !yield(k, v) {
68 return
69 }
70 }
71 }
72}
73
74var (
75 _ json.Unmarshaler = &Map[string, any]{}
76 _ json.Marshaler = &Map[string, any]{}
77)
78
79// UnmarshalJSON implements json.Unmarshaler.
80func (m *Map[K, V]) UnmarshalJSON(data []byte) error {
81 m.mu.Lock()
82 defer m.mu.Unlock()
83 m.inner = make(map[K]V)
84 return json.Unmarshal(data, &m.inner)
85}
86
87// MarshalJSON implements json.Marshaler.
88func (m *Map[K, V]) MarshalJSON() ([]byte, error) {
89 m.mu.RLock()
90 defer m.mu.RUnlock()
91 return json.Marshal(m.inner)
92}