forked from cosmos/cosmos-db
-
Notifications
You must be signed in to change notification settings - Fork 3
/
memdb_batch.go
107 lines (92 loc) · 1.87 KB
/
memdb_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
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
package db
import "fmt"
// memDBBatch operations
type opType int
const (
opTypeSet opType = iota + 1
opTypeDelete
)
type operation struct {
opType
key []byte
value []byte
}
// memDBBatch handles in-memory batching.
type memDBBatch struct {
db *MemDB
ops []operation
size int
}
var _ Batch = (*memDBBatch)(nil)
// newMemDBBatch creates a new memDBBatch
func newMemDBBatch(db *MemDB) *memDBBatch {
return &memDBBatch{
db: db,
ops: []operation{},
size: 0,
}
}
// Set implements Batch.
func (b *memDBBatch) Set(key, value []byte) error {
if len(key) == 0 {
return errKeyEmpty
}
if value == nil {
return errValueNil
}
if b.ops == nil {
return errBatchClosed
}
b.size += len(key) + len(value)
b.ops = append(b.ops, operation{opTypeSet, key, value})
return nil
}
// Delete implements Batch.
func (b *memDBBatch) Delete(key []byte) error {
if len(key) == 0 {
return errKeyEmpty
}
if b.ops == nil {
return errBatchClosed
}
b.size += len(key)
b.ops = append(b.ops, operation{opTypeDelete, key, nil})
return nil
}
// Write implements Batch.
func (b *memDBBatch) Write() error {
if b.ops == nil {
return errBatchClosed
}
b.db.mtx.Lock()
defer b.db.mtx.Unlock()
for _, op := range b.ops {
switch op.opType {
case opTypeSet:
b.db.set(op.key, op.value)
case opTypeDelete:
b.db.delete(op.key)
default:
return fmt.Errorf("unknown operation type %v (%v)", op.opType, op)
}
}
// Make sure batch cannot be used afterwards. Callers should still call Close(), for errors.
return b.Close()
}
// WriteSync implements Batch.
func (b *memDBBatch) WriteSync() error {
return b.Write()
}
// Close implements Batch.
func (b *memDBBatch) Close() error {
b.ops = nil
b.size = 0
return nil
}
// GetByteSize implements Batch
func (b *memDBBatch) GetByteSize() (int, error) {
if b.ops == nil {
return 0, errBatchClosed
}
return b.size, nil
}