-
Notifications
You must be signed in to change notification settings - Fork 5
/
engine.go
128 lines (93 loc) · 1.84 KB
/
engine.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
// The memory package implements an in-memory storage storage. This is primarily
// for testing or one-off analyses.
package memory
import (
"sync"
"github.com/chop-dbhi/origins/storage"
)
type Tx struct {
e *Engine
}
func (t *Tx) Get(p, k string) ([]byte, error) {
if b, ok := t.e.parts[p]; ok {
return b[k], nil
}
return nil, nil
}
func (t *Tx) Set(p, k string, v []byte) error {
var (
ok bool
b map[string][]byte
)
if b, ok = t.e.parts[p]; !ok {
b = make(map[string][]byte)
t.e.parts[p] = b
}
b[k] = v
return nil
}
func (t *Tx) Delete(p, k string) error {
if m, ok := t.e.parts[p]; ok {
delete(m, k)
}
return nil
}
func (t *Tx) Incr(p, k string) (uint64, error) {
var (
ok bool
id uint64
v []byte
b map[string][]byte
)
if b, ok = t.e.parts[p]; !ok {
b = make(map[string][]byte)
t.e.parts[p] = b
}
if v, ok = b[k]; ok {
id = storage.DecodeCounter(v)
}
id++
b[k] = storage.EncodeCounter(id)
return id, nil
}
// Engine is an in-memory store that keeps data in keyed parts.
type Engine struct {
parts map[string]map[string][]byte
sync.Mutex
}
func (e *Engine) Get(p, k string) ([]byte, error) {
e.Lock()
defer e.Unlock()
t := &Tx{e}
return t.Get(p, k)
}
func (e *Engine) Set(p, k string, v []byte) error {
e.Lock()
defer e.Unlock()
t := &Tx{e}
return t.Set(p, k, v)
}
func (e *Engine) Delete(p, k string) error {
e.Lock()
defer e.Unlock()
t := &Tx{e}
return t.Delete(p, k)
}
func (e *Engine) Incr(p, k string) (uint64, error) {
e.Lock()
defer e.Unlock()
t := &Tx{e}
return t.Incr(p, k)
}
func (e *Engine) Multi(f func(tx storage.Tx) error) error {
e.Lock()
defer e.Unlock()
return f(&Tx{e})
}
// Open initializes a new Engine and returns it.
func Init(opts storage.Options) (storage.Engine, error) {
e := Engine{
parts: make(map[string]map[string][]byte),
}
return &e, nil
}