forked from meshplus/bitxhub-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leveldb.go
96 lines (78 loc) · 1.58 KB
/
leveldb.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
package leveldb
import (
"github.com/axiomesh/axiom-kit/storage"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/errors"
"github.com/syndtr/goleveldb/leveldb/util"
)
type ldb struct {
db *leveldb.DB
}
func New(path string) (storage.Storage, error) {
db, err := leveldb.OpenFile(path, nil)
if err != nil {
return nil, err
}
return &ldb{
db: db,
}, nil
}
func (l *ldb) Put(key, value []byte) {
if err := l.db.Put(key, value, nil); err != nil {
panic(err)
}
}
func (l *ldb) Delete(key []byte) {
if err := l.db.Delete(key, nil); err != nil {
panic(err)
}
}
func (l *ldb) Get(key []byte) []byte {
val, err := l.db.Get(key, nil)
if err != nil {
if err == errors.ErrNotFound {
return nil
}
panic(err)
}
return val
}
func (l *ldb) Has(key []byte) bool {
return l.Get(key) != nil
}
func (l *ldb) Iterator(start, end []byte) storage.Iterator {
rg := &util.Range{
Start: start,
Limit: end,
}
it := l.db.NewIterator(rg, nil)
return &iter{iter: it}
}
func (l *ldb) Prefix(prefix []byte) storage.Iterator {
rg := util.BytesPrefix(prefix)
return &iter{iter: l.db.NewIterator(rg, nil)}
}
func (l *ldb) NewBatch() storage.Batch {
return &ldbBatch{
ldb: l.db,
batch: &leveldb.Batch{},
}
}
func (l *ldb) Close() error {
return l.db.Close()
}
type ldbBatch struct {
ldb *leveldb.DB
batch *leveldb.Batch
}
func (l *ldbBatch) Put(key, value []byte) {
l.batch.Put(key, value)
}
func (l *ldbBatch) Delete(key []byte) {
l.batch.Delete(key)
}
func (l *ldbBatch) Commit() {
if err := l.ldb.Write(l.batch, nil); err != nil {
panic(err)
}
}