-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.go
95 lines (89 loc) · 1.91 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
package godb
func (db *Storage) Write(bucket string, key string, payload []byte) error {
mtx := db.memTableMx.Get(bucket)
mtx.Lock()
defer mtx.Unlock()
m, ok := db.payloadStorage[bucket]
if ok {
delete(m, key)
}
if !db.diskKeyExists(bucket, key) {
_, ok := db.keysStorage[bucket]
if ok {
delete(db.keysStorage, bucket)
}
}
return db.diskWrite(bucket, key, payload)
}
func (db *Storage) Read(bucket string, key string) ([]byte, error) {
mtx := db.memTableMx.Get(bucket)
mtx.Lock()
defer mtx.Unlock()
m, ok := db.payloadStorage[bucket]
if !ok {
m = make(map[string][]byte)
}
cacheData, ok := m[key]
if !ok {
diskData, err := db.diskRead(bucket, key)
if err != nil {
return nil, err
}
m[key] = diskData
db.payloadStorage[bucket] = m
return diskData, nil
}
return cacheData, nil
}
func (db *Storage) Remove(bucket, key string) error {
mtx := db.memTableMx.Get(bucket)
mtx.Lock()
defer mtx.Unlock()
_, ok := db.keysStorage[bucket]
if ok {
delete(db.keysStorage, bucket)
}
m, ok := db.payloadStorage[bucket]
if ok {
delete(m, key)
}
return db.diskRemove(bucket, key)
}
func (db *Storage) RemoveAll(bucket string) error {
mtx := db.memTableMx.Get(bucket)
mtx.Lock()
defer mtx.Unlock()
_, ok := db.keysStorage[bucket]
if ok {
delete(db.keysStorage, bucket)
}
delete(db.payloadStorage, bucket)
return db.diskRemoveAll(bucket)
}
func (db *Storage) Keys(bucket string) ([]string, error) {
keys, ok := db.keysStorage[bucket]
if ok {
return keys, nil
}
keys, err := db.diskKeys(bucket)
if err != nil {
return nil, err
}
db.keysStorage[bucket] = keys
return keys, nil
}
func (db *Storage) ReadAll(bucket string) ([][]byte, error) {
buf := make([][]byte, 0, 64)
keys, err := db.Keys(bucket)
if err != nil {
return nil, err
}
for _, key := range keys {
data, err := db.Read(bucket, key)
if err != nil {
return nil, err
}
buf = append(buf, data)
}
return buf, nil
}