forked from astaxie/docker-registry
/
batch.go
70 lines (57 loc) · 1.07 KB
/
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
package driver
import (
"github.com/syndtr/goleveldb/leveldb"
)
type BatchPuter interface {
BatchPut([]Write) error
SyncBatchPut([]Write) error
}
type Write struct {
Key []byte
Value []byte
}
type WriteBatch struct {
d *leveldb.Batch
wb []Write
w BatchPuter
}
func (wb *WriteBatch) Close() {
wb.d.Reset()
wb.wb = wb.wb[0:0]
}
func (wb *WriteBatch) Put(key, value []byte) {
if value == nil {
value = []byte{}
}
wb.wb = append(wb.wb, Write{key, value})
}
func (wb *WriteBatch) Delete(key []byte) {
wb.wb = append(wb.wb, Write{key, nil})
}
func (wb *WriteBatch) Commit() error {
return wb.w.BatchPut(wb.wb)
}
func (wb *WriteBatch) SyncCommit() error {
return wb.w.SyncBatchPut(wb.wb)
}
func (wb *WriteBatch) Rollback() error {
wb.wb = wb.wb[0:0]
return nil
}
func (wb *WriteBatch) Data() []byte {
wb.d.Reset()
for _, w := range wb.wb {
if w.Value == nil {
wb.d.Delete(w.Key)
} else {
wb.d.Put(w.Key, w.Value)
}
}
return wb.d.Dump()
}
func NewWriteBatch(puter BatchPuter) *WriteBatch {
return &WriteBatch{
&leveldb.Batch{},
[]Write{},
puter}
}