forked from ailidani/paxi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcset.go
60 lines (51 loc) · 947 Bytes
/
cset.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
package lib
import "sync"
// CSet is concurrent set with generic data as interface{}
type CSet struct {
data map[interface{}]struct{}
sync.RWMutex
}
func NewCSet() *CSet {
return &CSet{
data: make(map[interface{}]struct{}),
}
}
func (s *CSet) Put(e interface{}) {
s.Lock()
defer s.Unlock()
s.data[e] = struct{}{}
}
// Get returns random element from set
func (s *CSet) Get() interface{} {
s.RLock()
defer s.Unlock()
for e := range s.data {
return e
}
return nil
}
func (s *CSet) Contains(e interface{}) bool {
s.RLock()
defer s.RUnlock()
_, exists := s.data[e]
return exists
}
func (s *CSet) Remove(e interface{}) {
s.Lock()
defer s.Unlock()
delete(s.data, e)
}
func (s *CSet) Size() int {
s.RLock()
defer s.RUnlock()
return len(s.data)
}
func (s *CSet) Array() []interface{} {
array := make([]interface{}, 0)
s.RLock()
defer s.RUnlock()
for e := range s.data {
array = append(array, e)
}
return array
}