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// Take gets an item and then deletes it.
60func (m *Map[K, V]) Take(key K) (V, bool) {
61 m.mu.Lock()
62 defer m.mu.Unlock()
63 v, ok := m.inner[key]
64 delete(m.inner, key)
65 return v, ok
66}
67
68// Seq2 returns an iter.Seq2 that yields key-value pairs from the map.
69func (m *Map[K, V]) Seq2() iter.Seq2[K, V] {
70 dst := make(map[K]V)
71 m.mu.RLock()
72 maps.Copy(dst, m.inner)
73 m.mu.RUnlock()
74 return func(yield func(K, V) bool) {
75 for k, v := range dst {
76 if !yield(k, v) {
77 return
78 }
79 }
80 }
81}
82
83// Seq returns an iter.Seq that yields values from the map.
84func (m *Map[K, V]) Seq() iter.Seq[V] {
85 dst := make(map[K]V)
86 m.mu.RLock()
87 maps.Copy(dst, m.inner)
88 m.mu.RUnlock()
89 return func(yield func(V) bool) {
90 for _, v := range dst {
91 if !yield(v) {
92 return
93 }
94 }
95 }
96}
97
98var (
99 _ json.Unmarshaler = &Map[string, any]{}
100 _ json.Marshaler = &Map[string, any]{}
101)
102
103// UnmarshalJSON implements json.Unmarshaler.
104func (m *Map[K, V]) UnmarshalJSON(data []byte) error {
105 m.mu.Lock()
106 defer m.mu.Unlock()
107 m.inner = make(map[K]V)
108 return json.Unmarshal(data, &m.inner)
109}
110
111// MarshalJSON implements json.Marshaler.
112func (m *Map[K, V]) MarshalJSON() ([]byte, error) {
113 m.mu.RLock()
114 defer m.mu.RUnlock()
115 return json.Marshal(m.inner)
116}