-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsafe_treeset.go
83 lines (68 loc) · 1.42 KB
/
safe_treeset.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
package utils
import (
"github.com/emirpasic/gods/utils"
"sync"
"github.com/emirpasic/gods/sets/treeset"
)
type Comparator func(a, b interface{}) int
type OrderSet struct {
s *treeset.Set // 这个有序集合,不是协程安全的
m sync.Mutex
l int //大小限制, only top n
}
func NewWith(comparator utils.Comparator, size int) *OrderSet {
return &OrderSet{s: treeset.NewWith(comparator), l: size}
}
func (ors *OrderSet) Add(items ...interface{}) {
ors.m.Lock()
ors.s.Add(items...)
ors.m.Unlock()
}
func (ors *OrderSet) AddTopN(items ...interface{}) {
ors.m.Lock()
ors.s.Add(items...)
if ors.s.Size() > ors.l {
ors.s.Remove(ors.s.Values()[ors.s.Size()-1])
}
ors.m.Unlock()
}
func (ors *OrderSet) Remove(items ...interface{}) {
ors.m.Lock()
ors.s.Remove(items...)
ors.m.Unlock()
}
func (ors *OrderSet) Contains(items ...interface{}) bool {
ors.m.Lock()
val := ors.s.Contains(items...)
ors.m.Unlock()
return val
}
func (ors *OrderSet) Empty() bool {
ors.m.Lock()
val := ors.s.Empty()
ors.m.Unlock()
return val
}
func (ors *OrderSet) Size() int {
ors.m.Lock()
val := ors.s.Size()
ors.m.Unlock()
return val
}
func (ors *OrderSet) Clear() {
ors.m.Lock()
ors.s.Clear()
ors.m.Unlock()
}
func (ors *OrderSet) Values() []interface{} {
ors.m.Lock()
val := ors.s.Values()
ors.m.Unlock()
return val
}
func (ors *OrderSet) String() string {
ors.m.Lock()
val := ors.s.String()
ors.m.Unlock()
return val
}