This repository has been archived by the owner on Sep 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.go
138 lines (127 loc) · 2.31 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
package store
import "os"
// MemoryStore provides an in-memory implementation of Store
// for testing purposes
type Memory struct {
storeBase
v map[string][]byte
meta map[string]string
}
func (m *Memory) Type() string {
return "memory"
}
func (m *Memory) MetaData() map[string]string {
m.RLock()
defer m.RUnlock()
if m.parentStore != nil {
return m.parentStore.(*Memory).MetaData()
}
res := map[string]string{}
for k, v := range m.meta {
res[k] = v
}
return res
}
func (m *Memory) SetMetaData(vals map[string]string) error {
m.Lock()
defer m.Unlock()
if m.parentStore != nil {
return m.parentStore.(*Memory).SetMetaData(vals)
}
m.meta = map[string]string{}
for k, v := range vals {
m.meta[k] = v
}
if n, ok := vals["Name"]; ok {
m.name = n
}
return nil
}
func (m *Memory) Open(codec Codec) error {
if codec == nil {
codec = DefaultCodec
}
m.Codec = codec
m.closer = func() {
m.v = nil
}
m.v = map[string][]byte{}
m.opened = true
md := m.MetaData()
if n, ok := md["Name"]; ok {
m.name = n
}
return nil
}
func (m *Memory) MakeSub(loc string) (Store, error) {
m.Lock()
defer m.Unlock()
m.panicIfClosed()
if res, ok := m.subStores[loc]; ok {
return res, nil
}
res := &Memory{}
res.Open(m.Codec)
addSub(m, res, loc)
return res, nil
}
func (m *Memory) Keys() ([]string, error) {
m.RLock()
m.panicIfClosed()
res := make([]string, 0, len(m.v))
for k := range m.v {
res = append(res, k)
}
m.RUnlock()
return res, nil
}
func (m *Memory) Load(key string, val interface{}) error {
m.RLock()
m.panicIfClosed()
v, ok := m.v[key]
m.RUnlock()
if !ok {
return os.ErrNotExist
}
if err := m.Decode(v, val); err != nil {
return err
}
if ro, ok := val.(ReadOnlySetter); ok {
ro.SetReadOnly(m.ReadOnly())
}
if bb, ok := val.(BundleSetter); ok {
n := m.Name()
if n != "" {
bb.SetBundle(n)
}
}
return nil
}
func (m *Memory) Save(key string, val interface{}) error {
m.Lock()
defer m.Unlock()
m.panicIfClosed()
if m.readOnly {
return UnWritable(key)
}
buf, err := m.Encode(val)
if err != nil {
return err
}
m.v[key] = buf
return nil
}
func (m *Memory) Remove(key string) error {
m.Lock()
defer m.Unlock()
m.panicIfClosed()
_, ok := m.v[key]
if ok {
if m.readOnly {
return UnWritable(key)
}
delete(m.v, key)
return nil
}
return os.ErrNotExist
}