-
Notifications
You must be signed in to change notification settings - Fork 5
/
set_fixed.go
64 lines (53 loc) · 1.13 KB
/
set_fixed.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
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package setutils
import (
"github.com/TeaOSLab/EdgeNode/internal/zero"
"sync"
)
type FixedSet struct {
maxSize int
locker sync.RWMutex
m map[interface{}]zero.Zero
keys []interface{}
}
func NewFixedSet(maxSize int) *FixedSet {
if maxSize <= 0 {
maxSize = 1024
}
return &FixedSet{
maxSize: maxSize,
m: map[interface{}]zero.Zero{},
}
}
func (this *FixedSet) Push(item interface{}) {
this.locker.Lock()
_, ok := this.m[item]
if !ok {
// 是否已满
if len(this.keys) == this.maxSize {
var firstKey = this.keys[0]
this.keys = this.keys[1:]
delete(this.m, firstKey)
}
this.m[item] = zero.New()
this.keys = append(this.keys, item)
}
this.locker.Unlock()
}
func (this *FixedSet) Has(item interface{}) bool {
this.locker.RLock()
defer this.locker.RUnlock()
_, ok := this.m[item]
return ok
}
func (this *FixedSet) Size() int {
this.locker.RLock()
defer this.locker.RUnlock()
return len(this.keys)
}
func (this *FixedSet) Reset() {
this.locker.Lock()
this.m = map[interface{}]zero.Zero{}
this.keys = nil
this.locker.Unlock()
}