forked from tendermint/tendermint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mem_batch.go
74 lines (61 loc) · 1.31 KB
/
mem_batch.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
package db
import "sync"
type atomicSetDeleter interface {
Mutex() *sync.Mutex
SetNoLock(key, value []byte)
SetNoLockSync(key, value []byte)
DeleteNoLock(key []byte)
DeleteNoLockSync(key []byte)
}
type memBatch struct {
db atomicSetDeleter
ops []operation
}
type opType int
const (
opTypeSet opType = 1
opTypeDelete opType = 2
)
type operation struct {
opType
key []byte
value []byte
}
func (mBatch *memBatch) Set(key, value []byte) {
mBatch.ops = append(mBatch.ops, operation{opTypeSet, key, value})
}
func (mBatch *memBatch) Delete(key []byte) {
mBatch.ops = append(mBatch.ops, operation{opTypeDelete, key, nil})
}
func (mBatch *memBatch) Write() {
mBatch.write(false)
}
func (mBatch *memBatch) WriteSync() {
mBatch.write(true)
}
func (mBatch *memBatch) Close() {
mBatch.ops = nil
}
func (mBatch *memBatch) write(doSync bool) {
if mtx := mBatch.db.Mutex(); mtx != nil {
mtx.Lock()
defer mtx.Unlock()
}
for i, op := range mBatch.ops {
if doSync && i == (len(mBatch.ops)-1) {
switch op.opType {
case opTypeSet:
mBatch.db.SetNoLockSync(op.key, op.value)
case opTypeDelete:
mBatch.db.DeleteNoLockSync(op.key)
}
break // we're done.
}
switch op.opType {
case opTypeSet:
mBatch.db.SetNoLock(op.key, op.value)
case opTypeDelete:
mBatch.db.DeleteNoLock(op.key)
}
}
}