This repository has been archived by the owner on Jun 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrapper.go
97 lines (75 loc) · 2.31 KB
/
wrapper.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package syncset
import (
"github.com/djordje200179/extendedlibrary/datastructures/iter"
"github.com/djordje200179/extendedlibrary/datastructures/sets"
"sync"
)
// Wrapper is a wrapper around a set that provides thread-safe access to the set.
// Locking is done through read-write mutex. This means that multiple goroutines can read from the set at the same time,
// but only one goroutine can write to the set at the same time.
type Wrapper[T any] struct {
set sets.Set[T]
mutex sync.RWMutex
}
// From creates a new Wrapper from the given set.
func From[T any](set sets.Set[T]) *Wrapper[T] {
return &Wrapper[T]{set, sync.RWMutex{}}
}
// Size returns the number of elements in the set.
func (w *Wrapper[T]) Size() int {
w.mutex.RLock()
defer w.mutex.RUnlock()
return w.set.Size()
}
// Add adds the given value to the set.
func (w *Wrapper[T]) Add(value T) {
w.mutex.Lock()
defer w.mutex.Unlock()
w.set.Add(value)
}
// Remove removes the given value from the set.
func (w *Wrapper[T]) Remove(value T) {
w.mutex.Lock()
defer w.mutex.Unlock()
w.set.Remove(value)
}
// Contains returns true if the set contains the given value.
func (w *Wrapper[T]) Contains(value T) bool {
w.mutex.RLock()
defer w.mutex.RUnlock()
return w.set.Contains(value)
}
// Clear removes all elements from the set.
func (w *Wrapper[T]) Clear() {
w.mutex.Lock()
defer w.mutex.Unlock()
w.set.Clear()
}
// Clone returns a shallow copy of the set.
func (w *Wrapper[T]) Clone() sets.Set[T] {
w.mutex.RLock()
defer w.mutex.RUnlock()
clonedSet := w.set.Clone()
return From[T](clonedSet)
}
// Iterator returns an iter.Iterator over the elements in the set.
func (w *Wrapper[T]) Iterator() iter.Iterator[T] {
return w.SetIterator()
}
// SetIterator returns an iterator over the elements in the set.
func (w *Wrapper[T]) SetIterator() sets.Iterator[T] {
return Iterator[T]{w.set.SetIterator(), &w.mutex}
}
// Stream streams the elements of the Set.
func (w *Wrapper[T]) Stream(yield func(T) bool) {
w.mutex.RLock()
defer w.mutex.RUnlock()
w.set.Stream(yield)
}
// Transaction executes the given update function with the set as an argument.
// The set is locked for writing during the execution of the update function.
func (w *Wrapper[T]) Transaction(updateFunction func(set sets.Set[T])) {
w.mutex.Lock()
defer w.mutex.Unlock()
updateFunction(w.set)
}