-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpleset.go
More file actions
78 lines (67 loc) · 1.58 KB
/
Copy pathsimpleset.go
File metadata and controls
78 lines (67 loc) · 1.58 KB
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
72
73
74
75
76
77
78
package sets
import (
"iter"
"sync"
)
// SimpleSet is a concurrency-safe set for generic comparable types.
// It relies purely on the standard library's map and RWMutex, providing
// optimal performance for standard read-heavy or mixed workloads.
type SimpleSet[K comparable] struct {
mu sync.RWMutex
items map[K]struct{}
}
// New initializes and returns a new Set.
func NewSimpleSet[K comparable]() *SimpleSet[K] {
return &SimpleSet[K]{
items: make(map[K]struct{}),
}
}
// Add inserts a key into the set.
func (s *SimpleSet[K]) Add(key K) {
s.mu.Lock()
s.items[key] = struct{}{}
s.mu.Unlock()
}
// Has performs an O(1) existence check for the key.
func (s *SimpleSet[K]) Has(key K) bool {
s.mu.RLock()
_, exists := s.items[key]
s.mu.RUnlock()
return exists
}
// Remove deletes a key from the set.
func (s *SimpleSet[K]) Remove(key K) {
s.mu.Lock()
delete(s.items, key)
s.mu.Unlock()
}
// Len returns the total number of items currently in the set.
func (s *SimpleSet[K]) Len() int {
s.mu.RLock()
count := len(s.items)
s.mu.RUnlock()
return count
}
// Len returns the total number of items currently in the set.
func (s *SimpleSet[K]) Size() int {
return s.Len()
}
func (s *SimpleSet[K]) Snapshot() []K {
s.mu.RLock()
snapshot := make([]K, len(s.items))
for key := range s.items {
snapshot = append(snapshot, key)
}
s.mu.RUnlock()
return snapshot
}
// Entries allows you to iterate over the items in the set.
func (s *SimpleSet[K]) Itterator() iter.Seq[K] {
return func(yield func(K) bool) {
for _, key := range s.Snapshot() {
if !yield(key) {
return
}
}
}
}