golang.org/x/tools/gopls@v0.15.3/internal/util/persistent/set.go (about)

     1  // Copyright 2023 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package persistent
     6  
     7  import "golang.org/x/tools/gopls/internal/util/constraints"
     8  
     9  // Set is a collection of elements of type K.
    10  //
    11  // It uses immutable data structures internally, so that sets can be cloned in
    12  // constant time.
    13  //
    14  // The zero value is a valid empty set.
    15  type Set[K constraints.Ordered] struct {
    16  	impl *Map[K, struct{}]
    17  }
    18  
    19  // Clone creates a copy of the receiver.
    20  func (s *Set[K]) Clone() *Set[K] {
    21  	clone := new(Set[K])
    22  	if s.impl != nil {
    23  		clone.impl = s.impl.Clone()
    24  	}
    25  	return clone
    26  }
    27  
    28  // Destroy destroys the set.
    29  //
    30  // After Destroy, the Set should not be used again.
    31  func (s *Set[K]) Destroy() {
    32  	if s.impl != nil {
    33  		s.impl.Destroy()
    34  	}
    35  }
    36  
    37  // Contains reports whether s contains the given key.
    38  func (s *Set[K]) Contains(key K) bool {
    39  	if s.impl == nil {
    40  		return false
    41  	}
    42  	_, ok := s.impl.Get(key)
    43  	return ok
    44  }
    45  
    46  // Range calls f sequentially in ascending key order for all entries in the set.
    47  func (s *Set[K]) Range(f func(key K)) {
    48  	if s.impl != nil {
    49  		s.impl.Range(func(key K, _ struct{}) {
    50  			f(key)
    51  		})
    52  	}
    53  }
    54  
    55  // AddAll adds all elements from other to the receiver set.
    56  func (s *Set[K]) AddAll(other *Set[K]) {
    57  	if other.impl != nil {
    58  		if s.impl == nil {
    59  			s.impl = new(Map[K, struct{}])
    60  		}
    61  		s.impl.SetAll(other.impl)
    62  	}
    63  }
    64  
    65  // Add adds an element to the set.
    66  func (s *Set[K]) Add(key K) {
    67  	if s.impl == nil {
    68  		s.impl = new(Map[K, struct{}])
    69  	}
    70  	s.impl.Set(key, struct{}{}, nil)
    71  }
    72  
    73  // Remove removes an element from the set.
    74  func (s *Set[K]) Remove(key K) {
    75  	if s.impl != nil {
    76  		s.impl.Delete(key)
    77  	}
    78  }