-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset.go
71 lines (61 loc) · 1009 Bytes
/
set.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package sg
import (
"iter"
"sync"
)
// Simple set implementation.
type Set[T comparable] struct {
sync.RWMutex
s map[T]struct{}
}
func NewSet[T comparable]() *Set[T] {
return &Set[T]{s: make(map[T]struct{})}
}
func (s *Set[T]) AddAll(k ...T) {
s.Lock()
defer s.Unlock()
for _, v := range k {
s.s[v] = struct{}{}
}
}
func (s *Set[T]) Add(k T) {
s.Lock()
defer s.Unlock()
s.s[k] = struct{}{}
}
func (s *Set[T]) Remove(k T) bool {
s.Lock()
defer s.Unlock()
_, ok := s.s[k]
delete(s.s, k)
return ok
}
func (s *Set[T]) Has(k T) bool {
s.RLock()
defer s.RUnlock()
_, ok := s.s[k]
return ok
}
func (s *Set[T]) Size() int {
s.RLock()
defer s.RUnlock()
return len(s.s)
}
func (s *Set[T]) Elements() iter.Seq[T] {
return func(yield func(T) bool) {
s.RLock()
defer s.RUnlock()
for k := range s.s {
yield(k)
}
}
}
func (s *Set[T]) Slice() []T {
s.RLock()
defer s.RUnlock()
keys := make([]T, 0, len(s.s))
for k := range s.s {
keys = append(keys, k)
}
return keys
}