github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/maps/skipmap/skipmap_safe.go (about) 1 package skipmap 2 3 import ( 4 "github.com/songzhibin97/go-baseutils/base/bcomparator" 5 "github.com/songzhibin97/go-baseutils/structure/maps" 6 "sync" 7 ) 8 9 var _ maps.Map[int, any] = (*MapSafe[int, any])(nil) 10 11 func NewSafe[K, V any](comparator bcomparator.Comparator[K]) *MapSafe[K, V] { 12 return &MapSafe[K, V]{ 13 unsafe: New[K, V](comparator), 14 } 15 } 16 17 type MapSafe[K any, V any] struct { 18 unsafe *Map[K, V] 19 lock sync.Mutex 20 } 21 22 func (s *MapSafe[K, V]) Put(key K, value V) { 23 s.lock.Lock() 24 defer s.lock.Unlock() 25 s.unsafe.Put(key, value) 26 27 } 28 29 func (s *MapSafe[K, V]) Get(key K) (V, bool) { 30 s.lock.Lock() 31 defer s.lock.Unlock() 32 return s.unsafe.Get(key) 33 } 34 35 func (s *MapSafe[K, V]) Remove(key K) { 36 s.lock.Lock() 37 defer s.lock.Unlock() 38 s.unsafe.Remove(key) 39 40 } 41 42 func (s *MapSafe[K, V]) Keys() []K { 43 s.lock.Lock() 44 defer s.lock.Unlock() 45 return s.unsafe.Keys() 46 } 47 48 func (s *MapSafe[K, V]) Empty() bool { 49 s.lock.Lock() 50 defer s.lock.Unlock() 51 return s.unsafe.Empty() 52 } 53 54 func (s *MapSafe[K, V]) Size() int { 55 s.lock.Lock() 56 defer s.lock.Unlock() 57 return s.unsafe.Size() 58 } 59 60 func (s *MapSafe[K, V]) Clear() { 61 s.lock.Lock() 62 defer s.lock.Unlock() 63 s.unsafe.Clear() 64 65 } 66 67 func (s *MapSafe[K, V]) Values() []V { 68 s.lock.Lock() 69 defer s.lock.Unlock() 70 return s.unsafe.Values() 71 } 72 73 func (s *MapSafe[K, V]) String() string { 74 s.lock.Lock() 75 defer s.lock.Unlock() 76 return s.unsafe.String() 77 } 78 79 func (s *MapSafe[K, V]) Store(key K, value V) { 80 s.lock.Lock() 81 defer s.lock.Unlock() 82 s.unsafe.Store(key, value) 83 84 } 85 86 func (s *MapSafe[K, V]) Load(key K) (V, bool) { 87 s.lock.Lock() 88 defer s.lock.Unlock() 89 return s.unsafe.Load(key) 90 } 91 92 func (s *MapSafe[K, V]) LoadAndDelete(key K) (V, bool) { 93 s.lock.Lock() 94 defer s.lock.Unlock() 95 return s.unsafe.LoadAndDelete(key) 96 } 97 98 func (s *MapSafe[K, V]) LoadOrStore(key K, value V) (V, bool) { 99 s.lock.Lock() 100 defer s.lock.Unlock() 101 return s.unsafe.LoadOrStore(key, value) 102 } 103 104 func (s *MapSafe[K, V]) LoadOrStoreLazy(key K, f func() V) (V, bool) { 105 s.lock.Lock() 106 defer s.lock.Unlock() 107 return s.unsafe.LoadOrStoreLazy(key, f) 108 } 109 110 func (s *MapSafe[K, V]) Delete(key K) bool { 111 s.lock.Lock() 112 defer s.lock.Unlock() 113 return s.unsafe.Delete(key) 114 } 115 116 func (s *MapSafe[K, V]) Range(f func(key K, value V) bool) { 117 s.lock.Lock() 118 defer s.lock.Unlock() 119 s.unsafe.Range(f) 120 121 } 122 123 func (s *MapSafe[K, V]) Len() int { 124 s.lock.Lock() 125 defer s.lock.Unlock() 126 return s.unsafe.Len() 127 }