-
Notifications
You must be signed in to change notification settings - Fork 5
/
leveldb_store.go
75 lines (65 loc) · 1.3 KB
/
leveldb_store.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
package main
import (
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/filter"
"github.com/syndtr/goleveldb/leveldb/opt"
"github.com/syndtr/goleveldb/leveldb/util"
)
type levelDBStore struct {
db *leveldb.DB
}
func newLevelDBStore(path string) Store {
// use 1 gb block cache
db, err := leveldb.OpenFile(path, &opt.Options{
BlockCacheCapacity: 10 * opt.GiB,
Filter: filter.NewBloomFilter(10),
})
if err != nil {
panic(err)
}
return &levelDBStore{
db: db,
}
}
func (t *levelDBStore) Scan(start []byte, batchSize int, fnShouldStop func(k []byte) bool) []*KV {
iter := t.db.NewIterator(&util.Range{
Start: start,
}, nil)
cnt := 0
var res []*KV
for iter.Next() {
if !iter.Valid() {
break
}
if fnShouldStop(iter.Key()) {
break
}
res = append(res, &KV{
K: append([]byte{}, iter.Key()...),
V: append([]byte{}, iter.Value()...),
})
cnt++
if cnt == batchSize {
break
}
}
iter.Release()
return res
}
func (t *levelDBStore) Exists(key []byte) bool {
b, _ := t.db.Has(key, nil)
return b
}
func (t *levelDBStore) Put(kv *KV) error {
return t.db.Put(kv.K, kv.V, nil)
}
func (t *levelDBStore) Get(key []byte) *KV {
v, _ := t.db.Get(key, nil)
return &KV{
K: key,
V: v,
}
}
func (t *levelDBStore) Close() {
t.db.Close()
}