package core

import "sync"

type SyncMap[K any, V any] struct {
	_map sync.Map
}

func (m *SyncMap[K, V]) Store(key K, value V) {
	m._map.Store(key, value)
}

func (m *SyncMap[K, V]) Load(key K) (value V, ok bool) {
	v, ok := m._map.Load(key)
	if ok {
		value = v.(V)
	}
	return
}

func (m *SyncMap[K, V]) Swap(key K, value V) (previous V, loaded bool) {
	v, loaded := m._map.Swap(key, value)
	if loaded {
		previous = v.(V)
	}
	return
}

func (m *SyncMap[K, V]) Delete(key K) {
	m._map.Delete(key)
}

func (m *SyncMap[K, V]) Clear() {
	m._map.Clear()
}

func (m *SyncMap[K, V]) Range(f func(key K, value V) bool) {
	m._map.Range(func(k, v any) bool {
		return f(k.(K), v.(V))
	})
}

func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
	v, loaded := m._map.LoadOrStore(key, value)
	if loaded {
		actual = v.(V)
	}
	return
}

func (m *SyncMap[K, V]) LoadAndDelete(key K) (value V, ok bool) {
	v, ok := m._map.LoadAndDelete(key)
	if ok {
		value = v.(V)
	}
	return
}

func (m *SyncMap[K, V]) CompareAndSwap(key K, old, new V) (swapped bool) {
	return m._map.CompareAndSwap(key, old, new)
}

func (m *SyncMap[K, V]) CompareAndDelete(key K, old V) (deleted bool) {
	return m._map.CompareAndDelete(key, old)
}
