github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/container/mutex_map.go (about) 1 //go:build go1.18 || go.19 || go.1.20 2 3 package container 4 5 import "sync" 6 7 type MutexMap[Key comparable, Value any] struct { 8 mu sync.Mutex 9 mp map[Key]Value 10 } 11 12 func (m *MutexMap[Key, Value]) LoadOk(k Key) (Value, bool) { 13 m.mu.Lock() 14 defer m.mu.Unlock() 15 if m.mp == nil { 16 return *new(Value), false 17 } 18 v, ok := m.mp[k] 19 return v, ok 20 } 21 22 func (m *MutexMap[Key, Value]) Load(k Key) Value { 23 v, _ := m.LoadOk(k) 24 return v 25 } 26 27 func (m *MutexMap[Key, Value]) Store(k Key, v Value) { 28 m.mu.Lock() 29 defer m.mu.Unlock() 30 if m.mp == nil { 31 m.mp = make(map[Key]Value) 32 } 33 m.mp[k] = v 34 } 35 36 func (m *MutexMap[Key, Value]) Range(fn func(key Key, v Value) bool) { 37 m.mu.Lock() 38 defer m.mu.Unlock() 39 if m.mp == nil { 40 return 41 } 42 for k, v := range m.mp { 43 if !fn(k, v) { 44 break 45 } 46 } 47 } 48 49 func (m *MutexMap[Key, Value]) Delete(k Key) { 50 m.mu.Lock() 51 defer m.mu.Unlock() 52 if m.mp == nil { 53 return 54 } 55 delete(m.mp, k) 56 } 57 58 func (m *MutexMap[Key, Value]) Len() int { 59 m.mu.Lock() 60 defer m.mu.Unlock() 61 return len(m.mp) 62 } 63 64 func (m *MutexMap[Key, Value]) Clean() map[Key]Value { 65 m.mu.Lock() 66 defer m.mu.Unlock() 67 old := m.mp 68 m.mp = make(map[Key]Value, 16) 69 return old 70 }