-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
119 lines (96 loc) · 1.82 KB
/
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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package pksafe
import (
"reflect"
"sync"
)
type set[T any] struct {
mutex sync.RWMutex
data map[int]T
alertChan chan T
}
type Set[T any] interface {
Add(item T) Set[T]
Alert() <-chan T
Delete(item T)
Clear()
Has(item T) (exist bool)
Size() (size int)
Value() (values []T)
ForEach(fn func(item T))
}
func NewSet[T any]() Set[T] { return &set[T]{data: make(map[int]T), alertChan: make(chan T)} }
func (s *set[T]) Add(item T) Set[T] {
if len(s.alertChan) > 0 {
<-s.alertChan
}
size := s.Size()
s.mutex.Lock()
defer s.mutex.Unlock()
s.data[size] = item
s.alertChan <- item
return s
}
func (s *set[T]) Alert() <-chan T { return s.alertChan }
func (s *set[T]) Delete(item T) {
s.mutex.RLock()
dataIndex := -1
for index, value := range s.data {
if reflect.DeepEqual(item, value) {
dataIndex = index
break
}
}
s.mutex.RUnlock()
if dataIndex == -1 {
return
}
s.mutex.Lock()
defer s.mutex.Unlock()
delete(s.data, dataIndex)
}
func (s *set[T]) Clear() {
size := s.Size()
s.mutex.Lock()
defer s.mutex.Unlock()
for i := 0; i < size; i++ {
delete(s.data, i)
}
}
func (s *set[T]) Has(item T) (exist bool) {
s.mutex.RLock()
defer s.mutex.RUnlock()
for _, value := range s.data {
if reflect.DeepEqual(item, value) {
exist = true
return
}
}
return
}
func (s *set[T]) Size() (size int) {
s.mutex.RLock()
defer s.mutex.RUnlock()
size = len(s.data)
return
}
func (s *set[T]) Value() (values []T) {
s.mutex.RLock()
defer s.mutex.RUnlock()
size := len(s.data)
for i := 0; i < size; i++ {
if value, exist := s.data[i]; exist {
values = append(values, value)
}
}
return
}
func (s *set[T]) ForEach(fn func(item T)) {
s.mutex.RLock()
defer s.mutex.RUnlock()
size := len(s.data)
for i := 0; i < size; i++ {
if value, exist := s.data[i]; exist {
fn(value)
}
}
}