github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/maps/hashmap/hashmap_safe.go (about)

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