/
syncmapdictionary.go
123 lines (95 loc) · 1.67 KB
/
syncmapdictionary.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
120
121
122
123
package storages
import (
"context"
"sync"
"time"
"golang.org/x/sync/errgroup"
)
type SyncMapDictionary struct {
sync.Map
pool DataPool
}
func NewSyncMapDictionary(pool DataPool) DataDictionary {
return &SyncMapDictionary{
pool: pool,
}
}
func (o *SyncMapDictionary) Add(key uint64, data []byte, expiration time.Time) error {
buf, err := o.pool.Copy(data, expiration)
if err != nil {
return err
}
o.Store(key, newRecord(buf, expiration))
return nil
}
func (o *SyncMapDictionary) Get(key uint64) (Buffer, error) {
v, ok := o.Load(key)
if !ok {
return Buffer{}, ErrKeyNotFound
}
rec, ok := v.(record)
if !ok {
return Buffer{}, ErrKeyNotFound
}
if rec.isExpired() {
return Buffer{}, ErrKeyExpired
}
return rec.get(), nil
}
func (o *SyncMapDictionary) Clean(ctx context.Context) error {
var (
wg errgroup.Group
)
wg.Go(func() error {
return o.pool.Clean(ctx)
})
wg.Go(func() error {
return o.cleanDictionary(ctx)
})
return wg.Wait()
}
func (o *SyncMapDictionary) cleanDictionary(ctx context.Context) error {
v := [100]uint64{}
index := -1
now := time.Now()
o.Range(func(key, value interface{}) bool {
select {
case <-ctx.Done():
return false
default:
}
rec, ok := value.(record)
if !ok {
return true
}
if rec.expiration.After(now) {
return true
}
index++
v[index], ok = key.(uint64)
if !ok {
return true
}
if index == len(v)-1 {
return false
}
return true
})
for _, key := range v {
select {
case <-ctx.Done():
return nil
default:
}
v, ok := o.LoadAndDelete(key)
if !ok {
continue
}
rec, ok := v.(record)
if !ok {
continue
}
rec.reset()
}
return nil
}