github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/container/rwmutex_map.go (about) 1 //go:build go1.18 || go.19 || go.1.20 2 3 package container 4 5 import ( 6 "sync" 7 ) 8 9 type RWMutexMap[Key any, Value any] struct { 10 mu sync.RWMutex 11 mp map[any]Value 12 } 13 14 func (m *RWMutexMap[Key, Value]) LoadOk(k Key) (Value, bool) { 15 m.mu.RLock() 16 defer m.mu.RUnlock() 17 if m.mp == nil { 18 return *new(Value), false 19 } 20 v, ok := m.mp[k] 21 return v, ok 22 } 23 24 func (m *RWMutexMap[Key, Value]) Load(k Key) Value { 25 m.mu.RLock() 26 defer m.mu.RUnlock() 27 if m.mp == nil { 28 return *new(Value) 29 } 30 return m.mp[k] 31 } 32 33 func (m *RWMutexMap[Key, Value]) Len() int { 34 m.mu.RLock() 35 defer m.mu.RUnlock() 36 return len(m.mp) 37 } 38 39 func (m *RWMutexMap[Key, Value]) Store(k Key, v Value) { 40 m.mu.Lock() 41 defer m.mu.Unlock() 42 if m.mp == nil { 43 m.mp = make(map[any]Value) 44 } 45 m.mp[k] = v 46 } 47 48 func (m *RWMutexMap[Key, Value]) Delete(k Key) { 49 m.mu.Lock() 50 defer m.mu.Unlock() 51 if m.mp == nil { 52 return 53 } 54 delete(m.mp, k) 55 }