github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/maps/treemap/treemap_safe.go (about) 1 package treemap 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 NewSafeWith[K, V any](comparator bcomparator.Comparator[K]) *MapSafe[K, V] { 12 return &MapSafe[K, V]{ 13 unsafe: NewWith[K, V](comparator), 14 } 15 } 16 17 func NewSafeWithIntComparator[V any]() *MapSafe[int, V] { 18 return &MapSafe[int, V]{ 19 unsafe: NewWithIntComparator[V](), 20 } 21 } 22 23 func NewSafeWithStringComparator[V any]() *MapSafe[string, V] { 24 return &MapSafe[string, V]{ 25 unsafe: NewWithStringComparator[V](), 26 } 27 } 28 29 type MapSafe[K any, V any] struct { 30 unsafe *Map[K, V] 31 lock sync.Mutex 32 } 33 34 func (s *MapSafe[K, V]) Put(key K, value V) { 35 s.lock.Lock() 36 defer s.lock.Unlock() 37 s.unsafe.Put(key, value) 38 39 } 40 41 func (s *MapSafe[K, V]) Get(key K) (V, bool) { 42 s.lock.Lock() 43 defer s.lock.Unlock() 44 return s.unsafe.Get(key) 45 } 46 47 func (s *MapSafe[K, V]) Remove(key K) { 48 s.lock.Lock() 49 defer s.lock.Unlock() 50 s.unsafe.Remove(key) 51 52 } 53 54 func (s *MapSafe[K, V]) Empty() bool { 55 s.lock.Lock() 56 defer s.lock.Unlock() 57 return s.unsafe.Empty() 58 } 59 60 func (s *MapSafe[K, V]) Size() int { 61 s.lock.Lock() 62 defer s.lock.Unlock() 63 return s.unsafe.Size() 64 } 65 66 func (s *MapSafe[K, V]) Keys() []K { 67 s.lock.Lock() 68 defer s.lock.Unlock() 69 return s.unsafe.Keys() 70 } 71 72 func (s *MapSafe[K, V]) Values() []V { 73 s.lock.Lock() 74 defer s.lock.Unlock() 75 return s.unsafe.Values() 76 } 77 78 func (s *MapSafe[K, V]) Clear() { 79 s.lock.Lock() 80 defer s.lock.Unlock() 81 s.unsafe.Clear() 82 83 } 84 85 func (s *MapSafe[K, V]) Min() (K, V) { 86 s.lock.Lock() 87 defer s.lock.Unlock() 88 return s.unsafe.Min() 89 } 90 91 func (s *MapSafe[K, V]) Max() (K, V) { 92 s.lock.Lock() 93 defer s.lock.Unlock() 94 return s.unsafe.Max() 95 } 96 97 func (s *MapSafe[K, V]) Floor(key K) (K, V) { 98 s.lock.Lock() 99 defer s.lock.Unlock() 100 return s.unsafe.Floor(key) 101 } 102 103 func (s *MapSafe[K, V]) Ceiling(key K) (K, V) { 104 s.lock.Lock() 105 defer s.lock.Unlock() 106 return s.unsafe.Ceiling(key) 107 } 108 109 func (s *MapSafe[K, V]) String() string { 110 s.lock.Lock() 111 defer s.lock.Unlock() 112 return s.unsafe.String() 113 } 114 115 func (s *MapSafe[K, V]) UnmarshalJSON(bytes []byte) error { 116 s.lock.Lock() 117 defer s.lock.Unlock() 118 return s.unsafe.UnmarshalJSON(bytes) 119 } 120 121 func (s *MapSafe[K, V]) MarshalJSON() ([]byte, error) { 122 s.lock.Lock() 123 defer s.lock.Unlock() 124 return s.unsafe.MarshalJSON() 125 }