forked from zuoyebang/bitalosdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merging_iter_heap.go
106 lines (94 loc) · 2.04 KB
/
merging_iter_heap.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
97
98
99
100
101
102
103
104
105
106
// Copyright 2021 The Bitalosdb author([email protected]) and other contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bitalosdb
type mergingIterItem struct {
index int
key InternalKey
value []byte
}
type mergingIterHeap struct {
cmp Compare
reverse bool
items []mergingIterItem
}
func (h *mergingIterHeap) len() int {
return len(h.items)
}
func (h *mergingIterHeap) clear() {
h.items = h.items[:0]
}
func (h *mergingIterHeap) less(i, j int) bool {
ikey, jkey := h.items[i].key, h.items[j].key
if c := h.cmp(ikey.UserKey, jkey.UserKey); c != 0 {
if h.reverse {
return c > 0
}
return c < 0
}
if h.reverse {
return ikey.Trailer < jkey.Trailer
}
return ikey.Trailer > jkey.Trailer
}
func (h *mergingIterHeap) swap(i, j int) {
h.items[i], h.items[j] = h.items[j], h.items[i]
}
func (h *mergingIterHeap) init() {
n := h.len()
for i := n/2 - 1; i >= 0; i-- {
h.down(i, n)
}
}
func (h *mergingIterHeap) fix(i int) {
if !h.down(i, h.len()) {
h.up(i)
}
}
func (h *mergingIterHeap) pop() *mergingIterItem {
n := h.len() - 1
h.swap(0, n)
h.down(0, n)
item := &h.items[n]
h.items = h.items[:n]
return item
}
func (h *mergingIterHeap) up(j int) {
for {
i := (j - 1) / 2
if i == j || !h.less(j, i) {
break
}
h.swap(i, j)
j = i
}
}
func (h *mergingIterHeap) down(i0, n int) bool {
i := i0
for {
j1 := 2*i + 1
if j1 >= n || j1 < 0 {
break
}
j := j1
if j2 := j1 + 1; j2 < n && h.less(j2, j1) {
j = j2
}
if !h.less(j, i) {
break
}
h.swap(i, j)
i = j
}
return i > i0
}