github.com/inazumav/sing-box@v0.0.0-20230926072359-ab51429a14f1/experimental/clashapi/compatible/map.go (about) 1 package compatible 2 3 import "sync" 4 5 // Map is a generics sync.Map 6 type Map[K comparable, V any] struct { 7 m sync.Map 8 } 9 10 func (m *Map[K, V]) Len() int { 11 var count int 12 m.m.Range(func(key, value any) bool { 13 count++ 14 return true 15 }) 16 return count 17 } 18 19 func (m *Map[K, V]) Load(key K) (V, bool) { 20 v, ok := m.m.Load(key) 21 if !ok { 22 return *new(V), false 23 } 24 25 return v.(V), ok 26 } 27 28 func (m *Map[K, V]) Store(key K, value V) { 29 m.m.Store(key, value) 30 } 31 32 func (m *Map[K, V]) Delete(key K) { 33 m.m.Delete(key) 34 } 35 36 func (m *Map[K, V]) Range(f func(key K, value V) bool) { 37 m.m.Range(func(key, value any) bool { 38 return f(key.(K), value.(V)) 39 }) 40 } 41 42 func (m *Map[K, V]) LoadOrStore(key K, value V) (V, bool) { 43 v, ok := m.m.LoadOrStore(key, value) 44 return v.(V), ok 45 } 46 47 func (m *Map[K, V]) LoadAndDelete(key K) (V, bool) { 48 v, ok := m.m.LoadAndDelete(key) 49 if !ok { 50 return *new(V), false 51 } 52 53 return v.(V), ok 54 } 55 56 func New[K comparable, V any]() *Map[K, V] { 57 return &Map[K, V]{m: sync.Map{}} 58 }