-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmemorysegment.go
68 lines (58 loc) · 1.52 KB
/
memorysegment.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
package keydb
//
// memorySegment wraps an im-memory binary Tree, so the number of items that can be inserted or removed
// in a transaction is limited by available memory. the Tree uses a nil Value to designate a key that
// has been removed from the table
//
type memorySegment struct {
tree *Tree
}
func newMemorySegment() segment {
ms := new(memorySegment)
ms.tree = &Tree{}
return ms
}
func (ms *memorySegment) Put(key []byte, value []byte) error {
ms.tree.Insert(key, value)
return nil
}
func (ms *memorySegment) Get(key []byte) ([]byte, error) {
value, ok := ms.tree.Find(key)
if !ok {
return nil, KeyNotFound
}
return value, nil
}
func (ms *memorySegment) Remove(key []byte) ([]byte, error) {
value, ok := ms.tree.Remove(key)
if ok {
return value, nil
}
return nil, KeyNotFound
}
func (ms *memorySegment) Lookup(lower []byte, upper []byte) (LookupIterator, error) {
return &memorySegmentIterator{results: ms.tree.FindNodes(lower, upper), index: 0}, nil
}
func (ms *memorySegment) Close() error {
return nil
}
type memorySegmentIterator struct {
results []TreeEntry
index int
}
func (es *memorySegmentIterator) Next() (key []byte, value []byte, err error) {
if es.index >= len(es.results) {
return nil, nil, EndOfIterator
}
key = es.results[es.index].Key
value = es.results[es.index].Value
es.index++
return key, value, nil
}
func (es *memorySegmentIterator) peekKey() ([]byte, error) {
if es.index >= len(es.results) {
return nil, EndOfIterator
}
key := es.results[es.index].Key
return key, nil
}