Debian Codegraph @

gopls/internal/util/persistent/set.go

raw symbols SCIP
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 (
8 "iter"
9
10 "golang.org/x/tools/gopls/internal/util/constraints"
11 )
12
13 // Set is a collection of elements of type K.
14 //
15 // It uses immutable data structures internally, so that sets can be cloned in
16 // constant time.
17 //
18 // The zero value is a valid empty set.
19 type Set[K constraints.Ordered] struct {
20 impl *Map[K, struct{}]
21 }
22
23 // Clone creates a copy of the receiver.
24 func (s *Set[K]) Clone() *Set[K] {
25 clone := new(Set[K])
26 if s.impl != nil {
27 clone.impl = s.impl.Clone()
28 }
29 return clone
30 }
31
32 // Destroy destroys the set.
33 //
34 // After Destroy, the Set should not be used again.
35 func (s *Set[K]) Destroy() {
36 if s.impl != nil {
37 s.impl.Destroy()
38 }
39 }
40
41 // Contains reports whether s contains the given key.
42 func (s *Set[K]) Contains(key K) bool {
43 if s.impl == nil {
44 return false
45 }
46 _, ok := s.impl.Get(key)
47 return ok
48 }
49
50 // All returns the sequence of set elements in ascending order.
51 func (s *Set[K]) All() iter.Seq[K] {
52 return func(yield func(K) bool) {
53 if s.impl != nil {
54 s.impl.root.forEach(func(k, _ any) bool {
55 return yield(k.(K))
56 })
57 }
58 }
59 }
60
61 // AddAll adds all elements from other to the receiver set.
62 func (s *Set[K]) AddAll(other *Set[K]) {
63 if other.impl != nil {
64 if s.impl == nil {
65 s.impl = new(Map[K, struct{}])
66 }
67 s.impl.SetAll(other.impl)
68 }
69 }
70
71 // Add adds an element to the set.
72 func (s *Set[K]) Add(key K) {
73 if s.impl == nil {
74 s.impl = new(Map[K, struct{}])
75 }
76 s.impl.Set(key, struct{}{}, nil)
77 }
78
79 // Remove removes an element from the set.
80 func (s *Set[K]) Remove(key K) {
81 if s.impl != nil {
82 s.impl.Delete(key)
83 }
84 }