-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmemtable.go
More file actions
96 lines (80 loc) · 1.78 KB
/
Copy pathmemtable.go
File metadata and controls
96 lines (80 loc) · 1.78 KB
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 main
import (
"github.com/huandu/skiplist"
"math"
"sync"
)
type Memtable struct {
mu sync.RWMutex
data *skiplist.SkipList
size int // Approximate size in bytes
}
func NewMemtable() *Memtable {
return &Memtable{
data: skiplist.New(internalKeyComparable{}),
}
}
func (m *Memtable) Put(key InternalKey, value []byte) {
m.mu.Lock()
defer m.mu.Unlock()
m.data.Set(key, value)
m.size += len(key.UserKey) + len(value)
}
func (m *Memtable) Get(key []byte) ([]byte, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
searchKey := InternalKey{
UserKey: string(key),
SeqNum: math.MaxUint64,
Type: OpTypePut,
}
elem := m.data.Find(searchKey)
if elem == nil {
return nil, false // Not found
}
foundKey := elem.Key().(InternalKey)
if foundKey.UserKey != string(key) {
return nil, false // Not a match
}
if foundKey.Type == OpTypeDelete {
return nil, true // Found a tombstone
}
return elem.Value.([]byte), true
}
func (m *Memtable) ApproximateSize() int {
return m.size
}
// NewIterator returns an iterator over the memtable's contents.
func (m *Memtable) NewIterator() Iterator {
m.mu.RLock()
defer m.mu.RUnlock()
return &memtableIterator{
list: m.data,
}
}
type memtableIterator struct {
list *skiplist.SkipList
current *skiplist.Element
}
func (it *memtableIterator) Valid() bool {
return it.current != nil
}
func (it *memtableIterator) Key() InternalKey {
return it.current.Key().(InternalKey)
}
func (it *memtableIterator) Value() []byte {
return it.current.Value.([]byte)
}
func (it *memtableIterator) Next() {
it.current = it.current.Next()
}
func (it *memtableIterator) Close() error {
it.current = nil
return nil
}
func (it *memtableIterator) Error() error {
return nil
}
func (it *memtableIterator) SeekToFirst() {
it.current = it.list.Front()
}