github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/sets/linkedhashset/linkedhashset_safe.go (about)

     1  package linkedhashset
     2  
     3  import (
     4  	"github.com/songzhibin97/go-baseutils/structure/sets"
     5  	"sync"
     6  )
     7  
     8  var _ sets.Set[int] = (*SetSafe[int])(nil)
     9  
    10  func NewSafe[E comparable](values ...E) *SetSafe[E] {
    11  	return &SetSafe[E]{
    12  		unsafe: New[E](values...),
    13  	}
    14  }
    15  
    16  type SetSafe[E comparable] struct {
    17  	unsafe *Set[E]
    18  	lock   sync.Mutex
    19  }
    20  
    21  func (s *SetSafe[E]) Add(items ...E) {
    22  	s.lock.Lock()
    23  	defer s.lock.Unlock()
    24  	s.unsafe.Add(items...)
    25  
    26  }
    27  
    28  func (s *SetSafe[E]) Remove(items ...E) {
    29  	s.lock.Lock()
    30  	defer s.lock.Unlock()
    31  	s.unsafe.Remove(items...)
    32  
    33  }
    34  
    35  func (s *SetSafe[E]) Contains(items ...E) bool {
    36  	s.lock.Lock()
    37  	defer s.lock.Unlock()
    38  	return s.unsafe.Contains(items...)
    39  }
    40  
    41  func (s *SetSafe[E]) Empty() bool {
    42  	s.lock.Lock()
    43  	defer s.lock.Unlock()
    44  	return s.unsafe.Empty()
    45  }
    46  
    47  func (s *SetSafe[E]) Size() int {
    48  	s.lock.Lock()
    49  	defer s.lock.Unlock()
    50  	return s.unsafe.Size()
    51  }
    52  
    53  func (s *SetSafe[E]) Clear() {
    54  	s.lock.Lock()
    55  	defer s.lock.Unlock()
    56  	s.unsafe.Clear()
    57  
    58  }
    59  
    60  func (s *SetSafe[E]) Values() []E {
    61  	s.lock.Lock()
    62  	defer s.lock.Unlock()
    63  	return s.unsafe.Values()
    64  }
    65  
    66  func (s *SetSafe[E]) String() string {
    67  	s.lock.Lock()
    68  	defer s.lock.Unlock()
    69  	return s.unsafe.String()
    70  }
    71  
    72  func (s *SetSafe[E]) Intersection(another *Set[E]) *Set[E] {
    73  	s.lock.Lock()
    74  	defer s.lock.Unlock()
    75  	return s.unsafe.Intersection(another)
    76  }
    77  
    78  func (s *SetSafe[E]) Union(another *Set[E]) *Set[E] {
    79  	s.lock.Lock()
    80  	defer s.lock.Unlock()
    81  	return s.unsafe.Union(another)
    82  }
    83  
    84  func (s *SetSafe[E]) Difference(another *Set[E]) *Set[E] {
    85  	s.lock.Lock()
    86  	defer s.lock.Unlock()
    87  	return s.unsafe.Difference(another)
    88  }
    89  
    90  func (s *SetSafe[E]) UnmarshalJSON(bytes []byte) error {
    91  	s.lock.Lock()
    92  	defer s.lock.Unlock()
    93  	return s.unsafe.UnmarshalJSON(bytes)
    94  }
    95  
    96  func (s *SetSafe[E]) MarshalJSON() ([]byte, error) {
    97  	s.lock.Lock()
    98  	defer s.lock.Unlock()
    99  	return s.unsafe.MarshalJSON()
   100  }