github.com/ydb-platform/ydb-go-sdk/v3@v3.89.2/internal/xsync/set.go (about)

     1  package xsync
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  )
     7  
     8  type Set[T comparable] struct {
     9  	m    sync.Map
    10  	size atomic.Int32
    11  }
    12  
    13  func (s *Set[T]) Has(key T) bool {
    14  	_, ok := s.m.Load(key)
    15  
    16  	return ok
    17  }
    18  
    19  func (s *Set[T]) Add(key T) bool {
    20  	_, exists := s.m.LoadOrStore(key, struct{}{})
    21  
    22  	if !exists {
    23  		s.size.Add(1)
    24  	}
    25  
    26  	return !exists
    27  }
    28  
    29  func (s *Set[T]) Size() int {
    30  	return int(s.size.Load())
    31  }
    32  
    33  func (s *Set[T]) Range(f func(key T) bool) {
    34  	s.m.Range(func(k, v any) bool {
    35  		return f(k.(T)) //nolint:forcetypeassert
    36  	})
    37  }
    38  
    39  func (s *Set[T]) Values() []T {
    40  	values := make([]T, 0, s.size.Load())
    41  
    42  	s.m.Range(func(k, v any) bool {
    43  		values = append(values, k.(T)) //nolint:forcetypeassert
    44  
    45  		return true
    46  	})
    47  
    48  	return values
    49  }
    50  
    51  func (s *Set[T]) Remove(key T) bool {
    52  	_, exists := s.m.LoadAndDelete(key)
    53  
    54  	if exists {
    55  		s.size.Add(-1)
    56  	}
    57  
    58  	return exists
    59  }
    60  
    61  func (s *Set[T]) Clear() (removed int) {
    62  	s.m.Range(func(k, v any) bool {
    63  		removed++
    64  
    65  		s.m.Delete(k)
    66  
    67  		return true
    68  	})
    69  	s.size.Add(int32(-removed))
    70  
    71  	return removed
    72  }