github.com/dolthub/go-mysql-server@v0.18.0/internal/cmap/cmap.go (about) 1 package cmap 2 3 import "sync" 4 5 func NewMap[K comparable, V any]() *Map[K, V] { 6 return &Map[K, V]{ 7 m: make(map[K]V), 8 mu: sync.RWMutex{}, 9 } 10 } 11 12 type Map[K comparable, V any] struct { 13 m map[K]V 14 mu sync.RWMutex 15 } 16 17 func (m *Map[K, V]) Get(key K) (V, bool) { 18 m.mu.RLock() 19 defer m.mu.RUnlock() 20 v, exists := m.m[key] 21 return v, exists 22 } 23 24 func (m *Map[K, V]) Set(key K, v V) { 25 m.mu.Lock() 26 defer m.mu.Unlock() 27 m.m[key] = v 28 29 } 30 31 func (m *Map[K, V]) Del(key K) { 32 m.mu.Lock() 33 defer m.mu.Unlock() 34 delete(m.m, key) 35 } 36 37 func (m *Map[K, V]) Foreach(f func(key K, v V) error) error { 38 m.mu.RLock() 39 defer m.mu.RUnlock() 40 for k, v := range m.m { 41 if err := f(k, v); err != nil { 42 return err 43 } 44 } 45 return nil 46 } 47 48 func (m *Map[K, V]) FindForeach(f func(key K, v V) bool) (K, V, bool) { 49 m.mu.RLock() 50 defer m.mu.RUnlock() 51 for k, v := range m.m { 52 if f(k, v) { 53 return k, v, true 54 } 55 } 56 var ( 57 k K 58 v V 59 ) 60 return k, v, false 61 }