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	return func(yield func(V) bool) {
 86		for _, v := range m.Seq2() {
 87			if !yield(v) {
 88				return
 89			}
 90		}
 91	}
 92}
 93
 94var (
 95	_ json.Unmarshaler = &Map[string, any]{}
 96	_ json.Marshaler   = &Map[string, any]{}
 97)
 98
 99func (Map[K, V]) JSONSchemaAlias() any { //nolint
100	m := map[K]V{}
101	return m
102}
103
104// UnmarshalJSON implements json.Unmarshaler.
105func (m *Map[K, V]) UnmarshalJSON(data []byte) error {
106	m.mu.Lock()
107	defer m.mu.Unlock()
108	m.inner = make(map[K]V)
109	return json.Unmarshal(data, &m.inner)
110}
111
112// MarshalJSON implements json.Marshaler.
113func (m *Map[K, V]) MarshalJSON() ([]byte, error) {
114	m.mu.RLock()
115	defer m.mu.RUnlock()
116	return json.Marshal(m.inner)
117}