-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbtree.go
79 lines (66 loc) · 1.3 KB
/
btree.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
package nimbusdb
import (
"bytes"
"sync"
"github.com/google/btree"
"github.com/manosriram/nimbusdb/utils"
)
type BTree struct {
tree *btree.BTree
mu sync.RWMutex
}
type item struct {
key []byte
v KeyDirValue
}
var itemPool = sync.Pool{
New: func() interface{} {
return &item{}
},
}
func (it item) Less(i btree.Item) bool {
return bytes.Compare(it.key, i.(*item).key) < 0
}
func (b *BTree) Get(key []byte) *KeyDirValue {
it := itemPool.Get().(*item)
it.key = key
defer itemPool.Put(it)
i := b.tree.Get(it)
if i == nil {
return nil
}
return &i.(*item).v
}
func (b *BTree) Set(key []byte, value KeyDirValue) *KeyDirValue {
i := b.tree.ReplaceOrInsert(&item{key: key, v: value})
if i != nil {
return &i.(*item).v
}
return nil
}
func (b *BTree) Delete(key []byte) *KeyValuePair {
it := itemPool.Get().(*item)
it.key = key
defer itemPool.Put(it)
i := b.tree.Delete(&item{key: key})
if i != nil {
x := i.(*item)
return &KeyValuePair{
Key: x.key,
Value: x.v,
}
}
return nil
}
func (b *BTree) List() []*KeyValuePair {
var pairs []*KeyValuePair
b.tree.Ascend(func(it btree.Item) bool {
pairs = append(pairs, &KeyValuePair{
Key: it.(*item).key,
Value: it.(*item).v,
Ttl: utils.TimeUntilUnixNano(it.(*item).v.tstamp),
})
return true
})
return pairs
}