github.com/quantosnetwork/Quantos@v0.0.0-20220306172517-e20b28c5a29a/events/set/set.go (about)

     1  package set
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  )
     7  
     8  // Set objects are collections of strings. A value in the Set may only occur once,
     9  // it is unique in the Set's collection.
    10  type Set struct {
    11  	set   map[string]struct{}
    12  	mutex *sync.Mutex
    13  }
    14  
    15  // Add appends a new element with the given value to the Set object.
    16  // It returns an error if the value already in set.
    17  func (s *Set) Add(v string) error {
    18  	// Check for mutex
    19  	s.init()
    20  
    21  	// Lock this function
    22  	s.mutex.Lock()
    23  	defer s.mutex.Unlock()
    24  
    25  	// Init the set map if set is empty.
    26  	if s.set == nil {
    27  		s.set = make(map[string]struct{})
    28  	}
    29  
    30  	// Check for value exist.
    31  	if _, ok := s.set[v]; ok {
    32  		return fmt.Errorf("Value already in set.")
    33  	}
    34  
    35  	s.set[v] = struct{}{}
    36  	return nil
    37  }
    38  
    39  // Clear removes all elements from the Set object.
    40  func (s *Set) Clear() {
    41  	// Check for mutex
    42  	s.init()
    43  
    44  	// Lock this function
    45  	s.mutex.Lock()
    46  	defer s.mutex.Unlock()
    47  
    48  	s.set = nil
    49  }
    50  
    51  // Values returns a new list object that contains the values for each element
    52  // in the Set object.
    53  func (s *Set) Values() (keys []string) {
    54  	// Check for mutex
    55  	s.init()
    56  
    57  	// Lock this function
    58  	s.mutex.Lock()
    59  	defer s.mutex.Unlock()
    60  
    61  	keys = make([]string, 0, len(s.set))
    62  	for k := range s.set {
    63  		keys = append(keys, k)
    64  	}
    65  
    66  	return
    67  }
    68  
    69  // Has returns a boolean asserting whether an element is present with the
    70  // given value in the Set object or not.
    71  func (s *Set) Has(v string) (ok bool) {
    72  	// Check for mutex
    73  	s.init()
    74  
    75  	// Lock this function
    76  	s.mutex.Lock()
    77  	defer s.mutex.Unlock()
    78  
    79  	_, ok = s.set[v]
    80  
    81  	return
    82  }
    83  
    84  // init the set mutex
    85  func (s *Set) init() {
    86  	// Check for mutex
    87  	if s.mutex == nil {
    88  		s.mutex = &sync.Mutex{}
    89  	}
    90  }