github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/maps/hashbidimap/hashbidimap_safe.go (about) 1 package hashbidimap 2 3 import ( 4 "github.com/songzhibin97/go-baseutils/structure/maps" 5 "sync" 6 ) 7 8 var _ maps.BidiMap[int, int] = (*MapSafe[int, int])(nil) 9 10 func NewSafe[K comparable, V comparable]() *MapSafe[K, V] { 11 return &MapSafe[K, V]{ 12 unsafe: New[K, V](), 13 } 14 } 15 16 type MapSafe[K comparable, V comparable] struct { 17 unsafe *Map[K, V] 18 lock sync.Mutex 19 } 20 21 func (s *MapSafe[K, V]) Put(key K, value V) { 22 s.lock.Lock() 23 defer s.lock.Unlock() 24 s.unsafe.Put(key, value) 25 26 } 27 28 func (s *MapSafe[K, V]) Get(key K) (V, bool) { 29 s.lock.Lock() 30 defer s.lock.Unlock() 31 return s.unsafe.Get(key) 32 } 33 34 func (s *MapSafe[K, V]) GetKey(value V) (K, bool) { 35 s.lock.Lock() 36 defer s.lock.Unlock() 37 return s.unsafe.GetKey(value) 38 } 39 40 func (s *MapSafe[K, V]) Remove(key K) { 41 s.lock.Lock() 42 defer s.lock.Unlock() 43 s.unsafe.Remove(key) 44 45 } 46 47 func (s *MapSafe[K, V]) Empty() bool { 48 s.lock.Lock() 49 defer s.lock.Unlock() 50 return s.unsafe.Empty() 51 } 52 53 func (s *MapSafe[K, V]) Size() int { 54 s.lock.Lock() 55 defer s.lock.Unlock() 56 return s.unsafe.Size() 57 } 58 59 func (s *MapSafe[K, V]) Keys() []K { 60 s.lock.Lock() 61 defer s.lock.Unlock() 62 return s.unsafe.Keys() 63 } 64 65 func (s *MapSafe[K, V]) Values() []V { 66 s.lock.Lock() 67 defer s.lock.Unlock() 68 return s.unsafe.Values() 69 } 70 71 func (s *MapSafe[K, V]) Clear() { 72 s.lock.Lock() 73 defer s.lock.Unlock() 74 s.unsafe.Clear() 75 76 } 77 78 func (s *MapSafe[K, V]) String() string { 79 s.lock.Lock() 80 defer s.lock.Unlock() 81 return s.unsafe.String() 82 } 83 84 func (s *MapSafe[K, V]) UnmarshalJSON(bytes []byte) error { 85 s.lock.Lock() 86 defer s.lock.Unlock() 87 return s.unsafe.UnmarshalJSON(bytes) 88 } 89 90 func (s *MapSafe[K, V]) MarshalJSON() ([]byte, error) { 91 s.lock.Lock() 92 defer s.lock.Unlock() 93 return s.unsafe.MarshalJSON() 94 }