github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/container/syncMap_118.go (about) 1 //go:build go1.18 2 3 package container 4 5 import ( 6 "sync" 7 "sync/atomic" 8 ) 9 10 type SyncMap118[Key comparable, Value any] struct { 11 SMap sync.Map 12 length int64 13 } 14 15 func (s *SyncMap118[Key, Value]) LoadOk(k Key) (Value, bool) { 16 v, ok := s.SMap.Load(k) 17 if !ok { 18 return *new(Value), false 19 } 20 return v.(Value), ok 21 } 22 23 func (s *SyncMap118[Key, Value]) Store(k Key, v Value) { 24 _, loaded := s.SMap.LoadOrStore(k, v) 25 if !loaded { 26 atomic.AddInt64(&s.length, 1) 27 } 28 } 29 30 func (s *SyncMap118[Key, Value]) Delete(k Key) { 31 _, loaded := s.SMap.LoadAndDelete(k) 32 if loaded { 33 atomic.AddInt64(&s.length, -1) 34 } 35 } 36 37 func (s *SyncMap118[Key, Value]) Len() int { 38 return int(atomic.LoadInt64(&s.length)) 39 } 40 41 func (s *SyncMap118[Key, Value]) Range(fn func(key Key, value Value) bool) { 42 s.SMap.Range(func(key, value any) bool { 43 return fn(key.(Key), value.(Value)) 44 }) 45 }