-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.go
155 lines (124 loc) · 2.39 KB
/
memory.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
// Package memory is a in-memory store store
package memory
import (
"strings"
"sync"
"time"
"github.com/Just4Ease/nuMicro/store"
)
type memoryStore struct {
options store.Options
sync.RWMutex
values map[string]*memoryRecord
}
type memoryRecord struct {
r *store.Record
c time.Time
}
func (m *memoryStore) Init(opts ...store.Option) error {
for _, o := range opts {
o(&m.options)
}
return nil
}
func (m *memoryStore) List() ([]*store.Record, error) {
m.RLock()
defer m.RUnlock()
//nolint:prealloc
var values []*store.Record
for _, v := range m.values {
// get expiry
d := v.r.Expiry
t := time.Since(v.c)
if d > time.Duration(0) {
// expired
if t > d {
continue
}
// update expiry
v.r.Expiry -= t
v.c = time.Now()
}
values = append(values, v.r)
}
return values, nil
}
func (m *memoryStore) Read(key string, opts ...store.ReadOption) ([]*store.Record, error) {
m.RLock()
defer m.RUnlock()
var options store.ReadOptions
for _, o := range opts {
o(&options)
}
var vals []*memoryRecord
if options.Prefix {
for _, v := range m.values {
if !strings.HasPrefix(v.r.Key, key) {
continue
}
vals = append(vals, v)
}
} else if options.Suffix {
for _, v := range m.values {
if !strings.HasSuffix(v.r.Key, key) {
continue
}
vals = append(vals, v)
}
} else {
v, ok := m.values[key]
if !ok {
return nil, store.ErrNotFound
}
vals = []*memoryRecord{v}
}
//nolint:prealloc
var records []*store.Record
for _, v := range vals {
// get expiry
d := v.r.Expiry
t := time.Since(v.c)
// expired
if d > time.Duration(0) {
if t > d {
return nil, store.ErrNotFound
}
// update expiry
v.r.Expiry -= t
v.c = time.Now()
}
records = append(records, v.r)
}
return records, nil
}
func (m *memoryStore) Write(r *store.Record) error {
m.Lock()
defer m.Unlock()
// set the record
m.values[r.Key] = &memoryRecord{
r: r,
c: time.Now(),
}
return nil
}
func (m *memoryStore) Delete(key string) error {
m.Lock()
defer m.Unlock()
// delete the value
delete(m.values, key)
return nil
}
func (m *memoryStore) String() string {
return "memory"
}
// NewStore returns a new store.Store
func NewStore(opts ...store.Option) store.Store {
var options store.Options
for _, o := range opts {
o(&options)
}
return &memoryStore{
options: options,
values: make(map[string]*memoryRecord),
}
}