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

     1  package linkedhashmap
     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]{
    12  		unsafe: New[K, V](),
    13  	}
    14  }
    15  
    16  type MapSafe[K comparable, V any] 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]) Remove(key K) {
    35  	s.lock.Lock()
    36  	defer s.lock.Unlock()
    37  	s.unsafe.Remove(key)
    38  
    39  }
    40  
    41  func (s *MapSafe[K, V]) Empty() bool {
    42  	s.lock.Lock()
    43  	defer s.lock.Unlock()
    44  	return s.unsafe.Empty()
    45  }
    46  
    47  func (s *MapSafe[K, V]) Size() int {
    48  	s.lock.Lock()
    49  	defer s.lock.Unlock()
    50  	return s.unsafe.Size()
    51  }
    52  
    53  func (s *MapSafe[K, V]) Keys() []K {
    54  	s.lock.Lock()
    55  	defer s.lock.Unlock()
    56  	return s.unsafe.Keys()
    57  }
    58  
    59  func (s *MapSafe[K, V]) Values() []V {
    60  	s.lock.Lock()
    61  	defer s.lock.Unlock()
    62  	return s.unsafe.Values()
    63  }
    64  
    65  func (s *MapSafe[K, V]) Clear() {
    66  	s.lock.Lock()
    67  	defer s.lock.Unlock()
    68  	s.unsafe.Clear()
    69  
    70  }
    71  
    72  func (s *MapSafe[K, V]) String() string {
    73  	s.lock.Lock()
    74  	defer s.lock.Unlock()
    75  	return s.unsafe.String()
    76  }
    77  
    78  func (s *MapSafe[K, V]) UnmarshalJSON(data []byte) error {
    79  	s.lock.Lock()
    80  	defer s.lock.Unlock()
    81  	return s.unsafe.UnmarshalJSON(data)
    82  }
    83  
    84  func (s *MapSafe[K, V]) MarshalJSON() ([]byte, error) {
    85  	s.lock.Lock()
    86  	defer s.lock.Unlock()
    87  	return s.unsafe.MarshalJSON()
    88  }