Line data Source code
1 : // Copyright 2022 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package keyspanimpl
6 :
7 : import (
8 : "bytes"
9 : "cmp"
10 : "fmt"
11 : "slices"
12 :
13 : "github.com/cockroachdb/pebble/internal/base"
14 : "github.com/cockroachdb/pebble/internal/invariants"
15 : "github.com/cockroachdb/pebble/internal/keyspan"
16 : "github.com/cockroachdb/pebble/internal/manifest"
17 : )
18 :
19 : // TODO(jackson): Consider implementing an optimization to seek lower levels
20 : // past higher levels' RANGEKEYDELs. This would be analaogous to the
21 : // optimization pebble.mergingIter performs for RANGEDELs during point key
22 : // seeks. It may not be worth it, because range keys are rare and cascading
23 : // seeks would require introducing key comparisons to switchTo{Min,Max}Heap
24 : // where there currently are none.
25 :
26 : // TODO(jackson): There are several opportunities to use base.Equal in the
27 : // MergingIter implementation, but will require a bit of plumbing to thread the
28 : // Equal function.
29 :
30 : // MergingIter merges spans across levels of the LSM, exposing an iterator over
31 : // spans that yields sets of spans fragmented at unique user key boundaries.
32 : //
33 : // A MergingIter is initialized with an arbitrary number of child iterators over
34 : // fragmented spans. Each child iterator exposes fragmented key spans, such that
35 : // overlapping keys are surfaced in a single Span. Key spans from one child
36 : // iterator may overlap key spans from another child iterator arbitrarily.
37 : //
38 : // The spans combined by MergingIter will return spans with keys sorted by
39 : // trailer descending. If the MergingIter is configured with a Transformer, it's
40 : // permitted to modify the ordering of the spans' keys returned by MergingIter.
41 : //
42 : // # Algorithm
43 : //
44 : // The merging iterator wraps child iterators, merging and fragmenting spans
45 : // across levels. The high-level algorithm is:
46 : //
47 : // 1. Initialize the heap with bound keys from child iterators' spans.
48 : // 2. Find the next [or previous] two unique user keys' from bounds.
49 : // 3. Consider the span formed between the two unique user keys a candidate
50 : // span.
51 : // 4. Determine if any of the child iterators' spans overlap the candidate
52 : // span.
53 : // 4a. If any of the child iterator's current bounds are end keys
54 : // (during forward iteration) or start keys (during reverse
55 : // iteration), then all the spans with that bound overlap the
56 : // candidate span.
57 : // 4b. Apply the configured transform, which may remove keys.
58 : // 4c. If no spans overlap, forget the smallest (forward iteration)
59 : // or largest (reverse iteration) unique user key and advance
60 : // the iterators to the next unique user key. Start again from 3.
61 : //
62 : // # Detailed algorithm
63 : //
64 : // Each level (i0, i1, ...) has a user-provided input FragmentIterator. The
65 : // merging iterator steps through individual boundaries of the underlying
66 : // spans separately. If the underlying FragmentIterator has fragments
67 : // [a,b){#2,#1} [b,c){#1} the mergingIterLevel.{next,prev} step through:
68 : //
69 : // (a, start), (b, end), (b, start), (c, end)
70 : //
71 : // Note that (a, start) and (b, end) are observed ONCE each, despite two keys
72 : // sharing those bounds. Also note that (b, end) and (b, start) are two distinct
73 : // iterator positions of a mergingIterLevel.
74 : //
75 : // The merging iterator maintains a heap (min during forward iteration, max
76 : // during reverse iteration) containing the boundKeys. Each boundKey is a
77 : // 3-tuple holding the bound user key, whether the bound is a start or end key
78 : // and the set of keys from that level that have that bound. The heap orders
79 : // based on the boundKey's user key only.
80 : //
81 : // The merging iterator is responsible for merging spans across levels to
82 : // determine which span is next, but it's also responsible for fragmenting
83 : // overlapping spans. Consider the example:
84 : //
85 : // i0: b---d e-----h
86 : // i1: a---c h-----k
87 : // i2: a------------------------------p
88 : //
89 : // fragments: a-b-c-d-e-----h-----k----------p
90 : //
91 : // None of the individual child iterators contain a span with the exact bounds
92 : // [c,d), but the merging iterator must produce a span [c,d). To accomplish
93 : // this, the merging iterator visits every span between unique boundary user
94 : // keys. In the above example, this is:
95 : //
96 : // [a,b), [b,c), [c,d), [d,e), [e, h), [h, k), [k, p)
97 : //
98 : // The merging iterator first initializes the heap to prepare for iteration.
99 : // The description below discusses the mechanics of forward iteration after a
100 : // call to First, but the mechanics are similar for reverse iteration and
101 : // other positioning methods.
102 : //
103 : // During a call to First, the heap is initialized by seeking every
104 : // mergingIterLevel to the first bound of the first fragment. In the above
105 : // example, this seeks the child iterators to:
106 : //
107 : // i0: (b, boundKindFragmentStart, [ [b,d) ])
108 : // i1: (a, boundKindFragmentStart, [ [a,c) ])
109 : // i2: (a, boundKindFragmentStart, [ [a,p) ])
110 : //
111 : // After fixing up the heap, the root of the heap is a boundKey with the
112 : // smallest user key ('a' in the example). Once the heap is setup for iteration
113 : // in the appropriate direction and location, the merging iterator uses
114 : // find{Next,Prev}FragmentSet to find the next/previous span bounds.
115 : //
116 : // During forward iteration, the root of the heap's user key is the start key
117 : // key of next merged span. findNextFragmentSet sets m.start to this user
118 : // key. The heap may contain other boundKeys with the same user key if another
119 : // level has a fragment starting or ending at the same key, so the
120 : // findNextFragmentSet method pulls from the heap until it finds the first key
121 : // greater than m.start. This key is used as the end key.
122 : //
123 : // In the above example, this results in m.start = 'a', m.end = 'b' and child
124 : // iterators in the following positions:
125 : //
126 : // i0: (b, boundKindFragmentStart, [ [b,d) ])
127 : // i1: (c, boundKindFragmentEnd, [ [a,c) ])
128 : // i2: (p, boundKindFragmentEnd, [ [a,p) ])
129 : //
130 : // With the user key bounds of the next merged span established,
131 : // findNextFragmentSet must determine which, if any, fragments overlap the span.
132 : // During forward iteration any child iterator that is now positioned at an end
133 : // boundary has an overlapping span. (Justification: The child iterator's end
134 : // boundary is ≥ m.end. The corresponding start boundary must be ≤ m.start since
135 : // there were no other user keys between m.start and m.end. So the fragments
136 : // associated with the iterator's current end boundary have start and end bounds
137 : // such that start ≤ m.start < m.end ≤ end).
138 : //
139 : // findNextFragmentSet iterates over the levels, collecting keys from any child
140 : // iterators positioned at end boundaries. In the above example, i1 and i2 are
141 : // positioned at end boundaries, so findNextFragmentSet collects the keys of
142 : // [a,c) and [a,p). These spans contain the merging iterator's [m.start, m.end)
143 : // span, but they may also extend beyond the m.start and m.end. The merging
144 : // iterator returns the keys with the merging iter's m.start and m.end bounds,
145 : // preserving the underlying keys' sequence numbers, key kinds and values.
146 : //
147 : // A MergingIter is configured with a Transform that's applied to the span
148 : // before surfacing it to the iterator user. A Transform may remove keys
149 : // arbitrarily, but it may not modify the values themselves.
150 : //
151 : // It may be the case that findNextFragmentSet finds no levels positioned at end
152 : // boundaries, or that there are no spans remaining after applying a transform,
153 : // in which case the span [m.start, m.end) overlaps with nothing. In this case
154 : // findNextFragmentSet loops, repeating the above process again until it finds a
155 : // span that does contain keys.
156 : //
157 : // # Memory safety
158 : //
159 : // The FragmentIterator interface only guarantees stability of a Span and its
160 : // associated slices until the next positioning method is called. Adjacent Spans
161 : // may be contained in different sstables, requring the FragmentIterator
162 : // implementation to close one sstable, releasing its memory, before opening the
163 : // next. Most of the state used by the MergingIter is derived from spans at
164 : // current child iterator positions only, ensuring state is stable. The one
165 : // exception is the start bound during forward iteration and the end bound
166 : // during reverse iteration.
167 : //
168 : // If the heap root originates from an end boundary when findNextFragmentSet
169 : // begins, a Next on the heap root level may invalidate the end boundary. To
170 : // accommodate this, find{Next,Prev}FragmentSet copy the initial boundary if the
171 : // subsequent Next/Prev would move to the next span.
172 : type MergingIter struct {
173 : *MergingBuffers
174 : // start and end hold the bounds for the span currently under the
175 : // iterator position.
176 : //
177 : // Invariant: None of the levels' iterators contain spans with a bound
178 : // between start and end. For all bounds b, b ≤ start || b ≥ end.
179 : start, end []byte
180 :
181 : // transformer defines a transformation to be applied to a span before it's
182 : // yielded to the user. Transforming may filter individual keys contained
183 : // within the span.
184 : transformer keyspan.Transformer
185 : // span holds the iterator's current span. This span is used as the
186 : // destination for transforms. Every tranformed span overwrites the
187 : // previous.
188 : span keyspan.Span
189 : dir int8
190 :
191 : // alloc preallocates mergingIterLevel and mergingIterItems for use by the
192 : // merging iterator. As long as the merging iterator is used with
193 : // manifest.NumLevels+3 and fewer fragment iterators, the merging iterator
194 : // will not need to allocate upon initialization. The value NumLevels+3
195 : // mirrors the preallocated levels in iterAlloc used for point iterators.
196 : // Invariant: cap(levels) == cap(items)
197 : alloc struct {
198 : levels [manifest.NumLevels + 3]mergingIterLevel
199 : items [manifest.NumLevels + 3]mergingIterItem
200 : }
201 : }
202 :
203 : // MergingBuffers holds buffers used while merging keyspans.
204 : type MergingBuffers struct {
205 : // keys holds all of the keys across all levels that overlap the key span
206 : // [start, end), sorted by Trailer descending. This slice is reconstituted
207 : // in synthesizeKeys from each mergingIterLevel's keys every time the
208 : // [start, end) bounds change.
209 : //
210 : // Each element points into a child iterator's memory, so the keys may not
211 : // be directly modified.
212 : keys []keyspan.Key
213 : // levels holds levels allocated by MergingIter.init. The MergingIter will
214 : // prefer use of its `manifest.NumLevels+3` array, so this slice will be
215 : // longer if set.
216 : levels []mergingIterLevel
217 : wrapFn keyspan.WrapFn
218 : // heap holds a slice for the merging iterator heap allocated by
219 : // MergingIter.init. The MergingIter will prefer use of its
220 : // `manifest.NumLevels+3` items array, so this slice will be longer if set.
221 : heap mergingIterHeap
222 : // buf is a buffer used to save [start, end) boundary keys.
223 : buf []byte
224 : }
225 :
226 : // PrepareForReuse discards any excessively large buffers.
227 2 : func (bufs *MergingBuffers) PrepareForReuse() {
228 2 : if cap(bufs.buf) > keyspan.BufferReuseMaxCapacity {
229 0 : bufs.buf = nil
230 0 : }
231 : }
232 :
233 : // MergingIter implements the FragmentIterator interface.
234 : var _ keyspan.FragmentIterator = (*MergingIter)(nil)
235 :
236 : type mergingIterLevel struct {
237 : iter keyspan.FragmentIterator
238 :
239 : // heapKey holds the current key at this level for use within the heap.
240 : heapKey boundKey
241 : }
242 :
243 2 : func (l *mergingIterLevel) next() error {
244 2 : if l.heapKey.kind == boundKindFragmentStart {
245 2 : l.heapKey = boundKey{
246 2 : kind: boundKindFragmentEnd,
247 2 : key: l.heapKey.span.End,
248 2 : span: l.heapKey.span,
249 2 : }
250 2 : return nil
251 2 : }
252 2 : s, err := l.iter.Next()
253 2 : switch {
254 1 : case err != nil:
255 1 : return err
256 2 : case s == nil:
257 2 : l.heapKey = boundKey{kind: boundKindInvalid}
258 2 : return nil
259 2 : default:
260 2 : l.heapKey = boundKey{
261 2 : kind: boundKindFragmentStart,
262 2 : key: s.Start,
263 2 : span: s,
264 2 : }
265 2 : return nil
266 : }
267 : }
268 :
269 2 : func (l *mergingIterLevel) prev() error {
270 2 : if l.heapKey.kind == boundKindFragmentEnd {
271 2 : l.heapKey = boundKey{
272 2 : kind: boundKindFragmentStart,
273 2 : key: l.heapKey.span.Start,
274 2 : span: l.heapKey.span,
275 2 : }
276 2 : return nil
277 2 : }
278 2 : s, err := l.iter.Prev()
279 2 : switch {
280 1 : case err != nil:
281 1 : return err
282 2 : case s == nil:
283 2 : l.heapKey = boundKey{kind: boundKindInvalid}
284 2 : return nil
285 2 : default:
286 2 : l.heapKey = boundKey{
287 2 : kind: boundKindFragmentEnd,
288 2 : key: s.End,
289 2 : span: s,
290 2 : }
291 2 : return nil
292 : }
293 : }
294 :
295 : // Init initializes the merging iterator with the provided fragment iterators.
296 : func (m *MergingIter) Init(
297 : cmp base.Compare,
298 : transformer keyspan.Transformer,
299 : bufs *MergingBuffers,
300 : iters ...keyspan.FragmentIterator,
301 2 : ) {
302 2 : *m = MergingIter{
303 2 : MergingBuffers: bufs,
304 2 : transformer: transformer,
305 2 : }
306 2 : m.heap.cmp = cmp
307 2 : levels, items := m.levels, m.heap.items
308 2 :
309 2 : // Invariant: cap(levels) >= cap(items)
310 2 : // Invariant: cap(alloc.levels) == cap(alloc.items)
311 2 : if len(iters) <= len(m.alloc.levels) {
312 2 : // The slices allocated on the MergingIter struct are large enough.
313 2 : m.levels = m.alloc.levels[:len(iters)]
314 2 : m.heap.items = m.alloc.items[:0]
315 2 : } else if len(iters) <= cap(levels) {
316 0 : // The existing heap-allocated slices are large enough, so reuse them.
317 0 : m.levels = levels[:len(iters)]
318 0 : m.heap.items = items[:0]
319 2 : } else {
320 2 : // Heap allocate new slices.
321 2 : m.levels = make([]mergingIterLevel, len(iters))
322 2 : m.heap.items = make([]mergingIterItem, 0, len(iters))
323 2 : }
324 2 : for i := range m.levels {
325 2 : m.levels[i] = mergingIterLevel{iter: iters[i]}
326 2 : if m.wrapFn != nil {
327 0 : m.levels[i].iter = m.wrapFn(m.levels[i].iter)
328 0 : }
329 : }
330 : }
331 :
332 : // AddLevel adds a new level to the bottom of the merging iterator. AddLevel
333 : // must be called after Init and before any other method.
334 2 : func (m *MergingIter) AddLevel(iter keyspan.FragmentIterator) {
335 2 : if m.wrapFn != nil {
336 0 : iter = m.wrapFn(iter)
337 0 : }
338 2 : m.levels = append(m.levels, mergingIterLevel{iter: iter})
339 : }
340 :
341 : // SeekGE moves the iterator to the first span covering a key greater than
342 : // or equal to the given key. This is equivalent to seeking to the first
343 : // span with an end key greater than the given key.
344 2 : func (m *MergingIter) SeekGE(key []byte) (*keyspan.Span, error) {
345 2 : // SeekGE(k) seeks to the first span with an end key greater than the given
346 2 : // key. The merged span M that we're searching for might straddle the seek
347 2 : // `key`. In this case, the M.Start may be a key ≤ the seek key.
348 2 : //
349 2 : // Consider a SeekGE(dog) in the following example.
350 2 : //
351 2 : // i0: b---d e-----h
352 2 : // i1: a---c h-----k
353 2 : // i2: a------------------------------p
354 2 : // merged: a-b-c-d-e-----h-----k----------p
355 2 : //
356 2 : // The merged span M containing 'dog' is [d,e). The 'd' of the merged span
357 2 : // comes from i0's [b,d)'s end boundary. The [b,d) span does not cover any
358 2 : // key >= dog, so we cannot find the span by positioning the child iterators
359 2 : // using a SeekGE(dog).
360 2 : //
361 2 : // Instead, if we take all the child iterators' spans bounds:
362 2 : // a b c d e h k p
363 2 : // We want to partition them into keys ≤ `key` and keys > `key`.
364 2 : // dog
365 2 : // │
366 2 : // a b c d│e h k p
367 2 : // │
368 2 : // The largest key on the left of the partition forms the merged span's
369 2 : // start key, and the smallest key on the right of the partition forms the
370 2 : // merged span's end key. Recharacterized:
371 2 : //
372 2 : // M.Start: the largest boundary ≤ k of any child span
373 2 : // M.End: the smallest boundary > k of any child span
374 2 : //
375 2 : // The FragmentIterator interface doesn't implement seeking by all bounds,
376 2 : // it implements seeking by containment. A SeekGE(k) will ensure we observe
377 2 : // all start boundaries ≥ k and all end boundaries > k but does not ensure
378 2 : // we observe end boundaries = k or any boundaries < k. A SeekLT(k) will
379 2 : // ensure we observe all start boundaries < k and all end boundaries ≤ k but
380 2 : // does not ensure we observe any start boundaries = k or any boundaries >
381 2 : // k. This forces us to seek in one direction and step in the other.
382 2 : //
383 2 : // In a SeekGE, we want to end up oriented in the forward direction when
384 2 : // complete, so we begin with searching for M.Start by SeekLT-ing every
385 2 : // child iterator to `k`. For every child span found, we determine the
386 2 : // largest bound ≤ `k` and use it to initialize our max heap. The resulting
387 2 : // root of the max heap is a preliminary value for `M.Start`.
388 2 : for i := range m.levels {
389 2 : l := &m.levels[i]
390 2 : s, err := l.iter.SeekLT(key)
391 2 : switch {
392 1 : case err != nil:
393 1 : return nil, err
394 2 : case s == nil:
395 2 : l.heapKey = boundKey{kind: boundKindInvalid}
396 2 : case m.cmp(s.End, key) <= 0:
397 2 : l.heapKey = boundKey{
398 2 : kind: boundKindFragmentEnd,
399 2 : key: s.End,
400 2 : span: s,
401 2 : }
402 2 : default:
403 2 : // s.End > key && s.Start < key
404 2 : // We need to use this span's start bound, since that's the largest
405 2 : // bound ≤ key.
406 2 : l.heapKey = boundKey{
407 2 : kind: boundKindFragmentStart,
408 2 : key: s.Start,
409 2 : span: s,
410 2 : }
411 : }
412 : }
413 2 : m.initMaxHeap()
414 2 : if len(m.heap.items) == 0 {
415 2 : // There are no spans covering any key < `key`. There is no span that
416 2 : // straddles the seek key. Reorient the heap into a min heap and return
417 2 : // the first span we find in the forward direction.
418 2 : if err := m.switchToMinHeap(); err != nil {
419 1 : return nil, err
420 1 : }
421 2 : return m.findNextFragmentSet()
422 : }
423 :
424 : // The heap root is now the largest boundary key b such that:
425 : // 1. b < k
426 : // 2. b = k, and b is an end boundary
427 : // There's a third case that we will need to consider later, after we've
428 : // switched to a min heap:
429 : // 3. there exists a start boundary key b such that b = k.
430 : // A start boundary key equal to k would not be surfaced when we seeked all
431 : // the levels using SeekLT(k), since no key <k would be covered within a
432 : // span within an inclusive `k` start boundary.
433 : //
434 : // Assume that the tightest boundary ≤ k is the current heap root (cases 1 &
435 : // 2). After we switch to a min heap, we'll check for the third case and
436 : // adjust the start boundary if necessary.
437 2 : m.start = m.heap.items[0].boundKey.key
438 2 :
439 2 : // Before switching the direction of the heap, save a copy of the start
440 2 : // boundary if it's the end boundary of some child span. Next-ing the child
441 2 : // iterator might switch files and invalidate the memory of the bound.
442 2 : if m.heap.items[0].boundKey.kind == boundKindFragmentEnd {
443 2 : m.buf = append(m.buf[:0], m.start...)
444 2 : m.start = m.buf
445 2 : }
446 :
447 : // Switch to a min heap. This will move each level to the next bound in
448 : // every level, and then establish a min heap. This allows us to obtain the
449 : // smallest boundary key > `key`, which will serve as our candidate end
450 : // bound.
451 2 : if err := m.switchToMinHeap(); err != nil {
452 1 : return nil, err
453 2 : } else if len(m.heap.items) == 0 {
454 2 : return nil, nil
455 2 : }
456 :
457 : // Check for the case 3 described above. It's possible that when we switch
458 : // heap directions, we discover a start boundary of some child span that is
459 : // equal to the seek key `key`. In this case, we want this key to be our
460 : // start boundary.
461 2 : if m.heap.items[0].boundKey.kind == boundKindFragmentStart &&
462 2 : m.cmp(m.heap.items[0].boundKey.key, key) == 0 {
463 2 : // Call findNextFragmentSet, which will set m.start to the heap root and
464 2 : // proceed forward.
465 2 : return m.findNextFragmentSet()
466 2 : }
467 :
468 2 : m.end = m.heap.items[0].boundKey.key
469 2 : if found, s, err := m.synthesizeKeys(+1); err != nil {
470 0 : return nil, err
471 2 : } else if found && s != nil {
472 2 : return s, nil
473 2 : }
474 2 : return m.findNextFragmentSet()
475 : }
476 :
477 : // SeekLT moves the iterator to the last span covering a key less than the
478 : // given key. This is equivalent to seeking to the last span with a start
479 : // key less than the given key.
480 2 : func (m *MergingIter) SeekLT(key []byte) (*keyspan.Span, error) {
481 2 : // SeekLT(k) seeks to the last span with a start key less than the given
482 2 : // key. The merged span M that we're searching for might straddle the seek
483 2 : // `key`. In this case, the M.End may be a key ≥ the seek key.
484 2 : //
485 2 : // Consider a SeekLT(dog) in the following example.
486 2 : //
487 2 : // i0: b---d e-----h
488 2 : // i1: a---c h-----k
489 2 : // i2: a------------------------------p
490 2 : // merged: a-b-c-d-e-----h-----k----------p
491 2 : //
492 2 : // The merged span M containing the largest key <'dog' is [d,e). The 'e' of
493 2 : // the merged span comes from i0's [e,h)'s start boundary. The [e,h) span
494 2 : // does not cover any key < dog, so we cannot find the span by positioning
495 2 : // the child iterators using a SeekLT(dog).
496 2 : //
497 2 : // Instead, if we take all the child iterators' spans bounds:
498 2 : // a b c d e h k p
499 2 : // We want to partition them into keys < `key` and keys ≥ `key`.
500 2 : // dog
501 2 : // │
502 2 : // a b c d│e h k p
503 2 : // │
504 2 : // The largest key on the left of the partition forms the merged span's
505 2 : // start key, and the smallest key on the right of the partition forms the
506 2 : // merged span's end key. Recharacterized:
507 2 : //
508 2 : // M.Start: the largest boundary < k of any child span
509 2 : // M.End: the smallest boundary ≥ k of any child span
510 2 : //
511 2 : // The FragmentIterator interface doesn't implement seeking by all bounds,
512 2 : // it implements seeking by containment. A SeekGE(k) will ensure we observe
513 2 : // all start boundaries ≥ k and all end boundaries > k but does not ensure
514 2 : // we observe end boundaries = k or any boundaries < k. A SeekLT(k) will
515 2 : // ensure we observe all start boundaries < k and all end boundaries ≤ k but
516 2 : // does not ensure we observe any start boundaries = k or any boundaries >
517 2 : // k. This forces us to seek in one direction and step in the other.
518 2 : //
519 2 : // In a SeekLT, we want to end up oriented in the backward direction when
520 2 : // complete, so we begin with searching for M.End by SeekGE-ing every
521 2 : // child iterator to `k`. For every child span found, we determine the
522 2 : // smallest bound ≥ `k` and use it to initialize our min heap. The resulting
523 2 : // root of the min heap is a preliminary value for `M.End`.
524 2 : for i := range m.levels {
525 2 : l := &m.levels[i]
526 2 : s, err := l.iter.SeekGE(key)
527 2 : switch {
528 1 : case err != nil:
529 1 : return nil, err
530 2 : case s == nil:
531 2 : l.heapKey = boundKey{kind: boundKindInvalid}
532 2 : case m.cmp(s.Start, key) >= 0:
533 2 : l.heapKey = boundKey{
534 2 : kind: boundKindFragmentStart,
535 2 : key: s.Start,
536 2 : span: s,
537 2 : }
538 2 : default:
539 2 : // s.Start < key
540 2 : // We need to use this span's end bound, since that's the smallest
541 2 : // bound > key.
542 2 : l.heapKey = boundKey{
543 2 : kind: boundKindFragmentEnd,
544 2 : key: s.End,
545 2 : span: s,
546 2 : }
547 : }
548 : }
549 2 : m.initMinHeap()
550 2 : if len(m.heap.items) == 0 {
551 2 : // There are no spans covering any key ≥ `key`. There is no span that
552 2 : // straddles the seek key. Reorient the heap into a max heap and return
553 2 : // the first span we find in the reverse direction.
554 2 : if err := m.switchToMaxHeap(); err != nil {
555 0 : return nil, err
556 0 : }
557 2 : return m.findPrevFragmentSet()
558 : }
559 :
560 : // The heap root is now the smallest boundary key b such that:
561 : // 1. b > k
562 : // 2. b = k, and b is a start boundary
563 : // There's a third case that we will need to consider later, after we've
564 : // switched to a max heap:
565 : // 3. there exists an end boundary key b such that b = k.
566 : // An end boundary key equal to k would not be surfaced when we seeked all
567 : // the levels using SeekGE(k), since k would not be contained within the
568 : // exclusive end boundary.
569 : //
570 : // Assume that the tightest boundary ≥ k is the current heap root (cases 1 &
571 : // 2). After we switch to a max heap, we'll check for the third case and
572 : // adjust the end boundary if necessary.
573 2 : m.end = m.heap.items[0].boundKey.key
574 2 :
575 2 : // Before switching the direction of the heap, save a copy of the end
576 2 : // boundary if it's the start boundary of some child span. Prev-ing the
577 2 : // child iterator might switch files and invalidate the memory of the bound.
578 2 : if m.heap.items[0].boundKey.kind == boundKindFragmentStart {
579 2 : m.buf = append(m.buf[:0], m.end...)
580 2 : m.end = m.buf
581 2 : }
582 :
583 : // Switch to a max heap. This will move each level to the previous bound in
584 : // every level, and then establish a max heap. This allows us to obtain the
585 : // largest boundary key < `key`, which will serve as our candidate start
586 : // bound.
587 2 : if err := m.switchToMaxHeap(); err != nil {
588 0 : return nil, err
589 2 : } else if len(m.heap.items) == 0 {
590 2 : return nil, nil
591 2 : }
592 : // Check for the case 3 described above. It's possible that when we switch
593 : // heap directions, we discover an end boundary of some child span that is
594 : // equal to the seek key `key`. In this case, we want this key to be our end
595 : // boundary.
596 2 : if m.heap.items[0].boundKey.kind == boundKindFragmentEnd &&
597 2 : m.cmp(m.heap.items[0].boundKey.key, key) == 0 {
598 2 : // Call findPrevFragmentSet, which will set m.end to the heap root and
599 2 : // proceed backwards.
600 2 : return m.findPrevFragmentSet()
601 2 : }
602 :
603 2 : m.start = m.heap.items[0].boundKey.key
604 2 : if found, s, err := m.synthesizeKeys(-1); err != nil {
605 0 : return nil, err
606 2 : } else if found && s != nil {
607 2 : return s, nil
608 2 : }
609 2 : return m.findPrevFragmentSet()
610 : }
611 :
612 : // First seeks the iterator to the first span.
613 2 : func (m *MergingIter) First() (*keyspan.Span, error) {
614 2 : for i := range m.levels {
615 2 : s, err := m.levels[i].iter.First()
616 2 : switch {
617 1 : case err != nil:
618 1 : return nil, err
619 2 : case s == nil:
620 2 : m.levels[i].heapKey = boundKey{kind: boundKindInvalid}
621 2 : default:
622 2 : m.levels[i].heapKey = boundKey{
623 2 : kind: boundKindFragmentStart,
624 2 : key: s.Start,
625 2 : span: s,
626 2 : }
627 : }
628 : }
629 2 : m.initMinHeap()
630 2 : return m.findNextFragmentSet()
631 : }
632 :
633 : // Last seeks the iterator to the last span.
634 2 : func (m *MergingIter) Last() (*keyspan.Span, error) {
635 2 : for i := range m.levels {
636 2 : s, err := m.levels[i].iter.Last()
637 2 : switch {
638 1 : case err != nil:
639 1 : return nil, err
640 0 : case s == nil:
641 0 : m.levels[i].heapKey = boundKey{kind: boundKindInvalid}
642 2 : default:
643 2 : m.levels[i].heapKey = boundKey{
644 2 : kind: boundKindFragmentEnd,
645 2 : key: s.End,
646 2 : span: s,
647 2 : }
648 : }
649 : }
650 2 : m.initMaxHeap()
651 2 : return m.findPrevFragmentSet()
652 : }
653 :
654 : // Next advances the iterator to the next span.
655 2 : func (m *MergingIter) Next() (*keyspan.Span, error) {
656 2 : if m.dir == +1 && (m.end == nil || m.start == nil) {
657 0 : return nil, nil
658 0 : }
659 2 : if m.dir != +1 {
660 2 : if err := m.switchToMinHeap(); err != nil {
661 0 : return nil, err
662 0 : }
663 : }
664 2 : return m.findNextFragmentSet()
665 : }
666 :
667 : // Prev advances the iterator to the previous span.
668 2 : func (m *MergingIter) Prev() (*keyspan.Span, error) {
669 2 : if m.dir == -1 && (m.end == nil || m.start == nil) {
670 0 : return nil, nil
671 0 : }
672 2 : if m.dir != -1 {
673 2 : if err := m.switchToMaxHeap(); err != nil {
674 0 : return nil, err
675 0 : }
676 : }
677 2 : return m.findPrevFragmentSet()
678 : }
679 :
680 : // Close closes the iterator, releasing all acquired resources.
681 2 : func (m *MergingIter) Close() error {
682 2 : var err error
683 2 : for i := range m.levels {
684 2 : err = firstError(err, m.levels[i].iter.Close())
685 2 : }
686 2 : m.levels = nil
687 2 : m.heap.items = m.heap.items[:0]
688 2 : return err
689 : }
690 :
691 : // String implements fmt.Stringer.
692 0 : func (m *MergingIter) String() string {
693 0 : return "merging-keyspan"
694 0 : }
695 :
696 2 : func (m *MergingIter) initMinHeap() {
697 2 : m.dir = +1
698 2 : m.heap.reverse = false
699 2 : m.initHeap()
700 2 : }
701 :
702 2 : func (m *MergingIter) initMaxHeap() {
703 2 : m.dir = -1
704 2 : m.heap.reverse = true
705 2 : m.initHeap()
706 2 : }
707 :
708 2 : func (m *MergingIter) initHeap() {
709 2 : m.heap.items = m.heap.items[:0]
710 2 : for i := range m.levels {
711 2 : if l := &m.levels[i]; l.heapKey.kind != boundKindInvalid {
712 2 : m.heap.items = append(m.heap.items, mergingIterItem{
713 2 : index: i,
714 2 : boundKey: &l.heapKey,
715 2 : })
716 2 : }
717 : }
718 2 : m.heap.init()
719 : }
720 :
721 2 : func (m *MergingIter) switchToMinHeap() error {
722 2 : // switchToMinHeap reorients the heap for forward iteration, without moving
723 2 : // the current MergingIter position.
724 2 :
725 2 : // The iterator is currently positioned at the span [m.start, m.end),
726 2 : // oriented in the reverse direction, so each level's iterator is positioned
727 2 : // to the largest key ≤ m.start. To reorient in the forward direction, we
728 2 : // must advance each level's iterator to the smallest key ≥ m.end. Consider
729 2 : // this three-level example.
730 2 : //
731 2 : // i0: b---d e-----h
732 2 : // i1: a---c h-----k
733 2 : // i2: a------------------------------p
734 2 : //
735 2 : // merged: a-b-c-d-e-----h-----k----------p
736 2 : //
737 2 : // If currently positioned at the merged span [c,d), then the level
738 2 : // iterators' heap keys are:
739 2 : //
740 2 : // i0: (b, [b, d)) i1: (c, [a,c)) i2: (a, [a,p))
741 2 : //
742 2 : // Reversing the heap should not move the merging iterator and should not
743 2 : // change the current [m.start, m.end) bounds. It should only prepare for
744 2 : // forward iteration by updating the child iterators' heap keys to:
745 2 : //
746 2 : // i0: (d, [b, d)) i1: (h, [h,k)) i2: (p, [a,p))
747 2 : //
748 2 : // In every level the first key ≥ m.end is the next in the iterator.
749 2 : // Justification: Suppose not and a level iterator's next key was some key k
750 2 : // such that k < m.end. The max-heap invariant dictates that the current
751 2 : // iterator position is the largest entry with a user key ≥ m.start. This
752 2 : // means k > m.start. We started with the assumption that k < m.end, so
753 2 : // m.start < k < m.end. But then k is between our current span bounds,
754 2 : // and reverse iteration would have constructed the current interval to be
755 2 : // [k, m.end) not [m.start, m.end).
756 2 :
757 2 : if invariants.Enabled {
758 2 : for i := range m.levels {
759 2 : l := &m.levels[i]
760 2 : if l.heapKey.kind != boundKindInvalid && m.cmp(l.heapKey.key, m.start) > 0 {
761 0 : panic("pebble: invariant violation: max-heap key > m.start")
762 : }
763 : }
764 : }
765 :
766 2 : for i := range m.levels {
767 2 : if err := m.levels[i].next(); err != nil {
768 1 : return err
769 1 : }
770 : }
771 2 : m.initMinHeap()
772 2 : return nil
773 : }
774 :
775 2 : func (m *MergingIter) switchToMaxHeap() error {
776 2 : // switchToMaxHeap reorients the heap for reverse iteration, without moving
777 2 : // the current MergingIter position.
778 2 :
779 2 : // The iterator is currently positioned at the span [m.start, m.end),
780 2 : // oriented in the forward direction. Each level's iterator is positioned at
781 2 : // the smallest bound ≥ m.end. To reorient in the reverse direction, we must
782 2 : // move each level's iterator to the largest key ≤ m.start. Consider this
783 2 : // three-level example.
784 2 : //
785 2 : // i0: b---d e-----h
786 2 : // i1: a---c h-----k
787 2 : // i2: a------------------------------p
788 2 : //
789 2 : // merged: a-b-c-d-e-----h-----k----------p
790 2 : //
791 2 : // If currently positioned at the merged span [c,d), then the level
792 2 : // iterators' heap keys are:
793 2 : //
794 2 : // i0: (d, [b, d)) i1: (h, [h,k)) i2: (p, [a,p))
795 2 : //
796 2 : // Reversing the heap should not move the merging iterator and should not
797 2 : // change the current [m.start, m.end) bounds. It should only prepare for
798 2 : // reverse iteration by updating the child iterators' heap keys to:
799 2 : //
800 2 : // i0: (b, [b, d)) i1: (c, [a,c)) i2: (a, [a,p))
801 2 : //
802 2 : // In every level the largest key ≤ m.start is the prev in the iterator.
803 2 : // Justification: Suppose not and a level iterator's prev key was some key k
804 2 : // such that k > m.start. The min-heap invariant dictates that the current
805 2 : // iterator position is the smallest entry with a user key ≥ m.end. This
806 2 : // means k < m.end, otherwise the iterator would be positioned at k. We
807 2 : // started with the assumption that k > m.start, so m.start < k < m.end. But
808 2 : // then k is between our current span bounds, and reverse iteration
809 2 : // would have constructed the current interval to be [m.start, k) not
810 2 : // [m.start, m.end).
811 2 :
812 2 : if invariants.Enabled {
813 2 : for i := range m.levels {
814 2 : l := &m.levels[i]
815 2 : if l.heapKey.kind != boundKindInvalid && m.cmp(l.heapKey.key, m.end) < 0 {
816 0 : panic("pebble: invariant violation: min-heap key < m.end")
817 : }
818 : }
819 : }
820 :
821 2 : for i := range m.levels {
822 2 : if err := m.levels[i].prev(); err != nil {
823 0 : return err
824 0 : }
825 : }
826 2 : m.initMaxHeap()
827 2 : return nil
828 : }
829 :
830 2 : func (m *MergingIter) cmp(a, b []byte) int {
831 2 : return m.heap.cmp(a, b)
832 2 : }
833 :
834 2 : func (m *MergingIter) findNextFragmentSet() (*keyspan.Span, error) {
835 2 : // Each iteration of this loop considers a new merged span between unique
836 2 : // user keys. An iteration may find that there exists no overlap for a given
837 2 : // span, (eg, if the spans [a,b), [d, e) exist within level iterators, the
838 2 : // below loop will still consider [b,d) before continuing to [d, e)). It
839 2 : // returns when it finds a span that is covered by at least one key.
840 2 :
841 2 : for m.heap.len() > 0 {
842 2 : // Initialize the next span's start bound. SeekGE and First prepare the
843 2 : // heap without advancing. Next leaves the heap in a state such that the
844 2 : // root is the smallest bound key equal to the returned span's end key,
845 2 : // so the heap is already positioned at the next merged span's start key.
846 2 :
847 2 : // NB: m.heapRoot() might be either an end boundary OR a start boundary
848 2 : // of a level's span. Both end and start boundaries may still be a start
849 2 : // key of a span in the set of fragmented spans returned by MergingIter.
850 2 : // Consider the scenario:
851 2 : // a----------l #1
852 2 : // b-----------m #2
853 2 : //
854 2 : // The merged, fully-fragmented spans that MergingIter exposes to the caller
855 2 : // have bounds:
856 2 : // a-b #1
857 2 : // b--------l #1
858 2 : // b--------l #2
859 2 : // l-m #2
860 2 : //
861 2 : // When advancing to l-m#2, we must set m.start to 'l', which originated
862 2 : // from [a,l)#1's end boundary.
863 2 : m.start = m.heap.items[0].boundKey.key
864 2 :
865 2 : // Before calling nextEntry, consider whether it might invalidate our
866 2 : // start boundary. If the start boundary key originated from an end
867 2 : // boundary, then we need to copy the start key before advancing the
868 2 : // underlying iterator to the next Span.
869 2 : if m.heap.items[0].boundKey.kind == boundKindFragmentEnd {
870 2 : m.buf = append(m.buf[:0], m.start...)
871 2 : m.start = m.buf
872 2 : }
873 :
874 : // There may be many entries all with the same user key. Spans in other
875 : // levels may also start or end at this same user key. For eg:
876 : // L1: [a, c) [c, d)
877 : // L2: [c, e)
878 : // If we're positioned at L1's end(c) end boundary, we want to advance
879 : // to the first bound > c.
880 2 : if err := m.nextEntry(); err != nil {
881 1 : return nil, err
882 1 : }
883 2 : for len(m.heap.items) > 0 && m.cmp(m.heapRoot(), m.start) == 0 {
884 2 : if err := m.nextEntry(); err != nil {
885 0 : return nil, err
886 0 : }
887 : }
888 2 : if len(m.heap.items) == 0 {
889 2 : break
890 : }
891 :
892 : // The current entry at the top of the heap is the first key > m.start.
893 : // It must become the end bound for the span we will return to the user.
894 : // In the above example, the root of the heap is L1's end(d).
895 2 : m.end = m.heap.items[0].boundKey.key
896 2 :
897 2 : // Each level within m.levels may have a span that overlaps the
898 2 : // fragmented key span [m.start, m.end). Update m.keys to point to them
899 2 : // and sort them by kind, sequence number. There may not be any keys
900 2 : // defined over [m.start, m.end) if we're between the end of one span
901 2 : // and the start of the next, OR if the configured transform filters any
902 2 : // keys out. We allow empty spans that were emitted by child iterators, but
903 2 : // we elide empty spans created by the mergingIter itself that don't overlap
904 2 : // with any child iterator returned spans (i.e. empty spans that bridge two
905 2 : // distinct child-iterator-defined spans).
906 2 : if found, s, err := m.synthesizeKeys(+1); err != nil {
907 0 : return nil, err
908 2 : } else if found && s != nil {
909 2 : return s, nil
910 2 : }
911 : }
912 : // Exhausted.
913 2 : m.clear()
914 2 : return nil, nil
915 : }
916 :
917 2 : func (m *MergingIter) findPrevFragmentSet() (*keyspan.Span, error) {
918 2 : // Each iteration of this loop considers a new merged span between unique
919 2 : // user keys. An iteration may find that there exists no overlap for a given
920 2 : // span, (eg, if the spans [a,b), [d, e) exist within level iterators, the
921 2 : // below loop will still consider [b,d) before continuing to [a, b)). It
922 2 : // returns when it finds a span that is covered by at least one key.
923 2 :
924 2 : for m.heap.len() > 0 {
925 2 : // Initialize the next span's end bound. SeekLT and Last prepare the
926 2 : // heap without advancing. Prev leaves the heap in a state such that the
927 2 : // root is the largest bound key equal to the returned span's start key,
928 2 : // so the heap is already positioned at the next merged span's end key.
929 2 :
930 2 : // NB: m.heapRoot() might be either an end boundary OR a start boundary
931 2 : // of a level's span. Both end and start boundaries may still be a start
932 2 : // key of a span returned by MergingIter. Consider the scenario:
933 2 : // a----------l #2
934 2 : // b-----------m #1
935 2 : //
936 2 : // The merged, fully-fragmented spans that MergingIter exposes to the caller
937 2 : // have bounds:
938 2 : // a-b #2
939 2 : // b--------l #2
940 2 : // b--------l #1
941 2 : // l-m #1
942 2 : //
943 2 : // When Preving to a-b#2, we must set m.end to 'b', which originated
944 2 : // from [b,m)#1's start boundary.
945 2 : m.end = m.heap.items[0].boundKey.key
946 2 :
947 2 : // Before calling prevEntry, consider whether it might invalidate our
948 2 : // end boundary. If the end boundary key originated from a start
949 2 : // boundary, then we need to copy the end key before advancing the
950 2 : // underlying iterator to the previous Span.
951 2 : if m.heap.items[0].boundKey.kind == boundKindFragmentStart {
952 2 : m.buf = append(m.buf[:0], m.end...)
953 2 : m.end = m.buf
954 2 : }
955 :
956 : // There may be many entries all with the same user key. Spans in other
957 : // levels may also start or end at this same user key. For eg:
958 : // L1: [a, c) [c, d)
959 : // L2: [c, e)
960 : // If we're positioned at L1's start(c) start boundary, we want to prev
961 : // to move to the first bound < c.
962 2 : if err := m.prevEntry(); err != nil {
963 1 : return nil, err
964 1 : }
965 2 : for len(m.heap.items) > 0 && m.cmp(m.heapRoot(), m.end) == 0 {
966 2 : if err := m.prevEntry(); err != nil {
967 0 : return nil, err
968 0 : }
969 : }
970 2 : if len(m.heap.items) == 0 {
971 2 : break
972 : }
973 :
974 : // The current entry at the top of the heap is the first key < m.end.
975 : // It must become the start bound for the span we will return to the
976 : // user. In the above example, the root of the heap is L1's start(a).
977 2 : m.start = m.heap.items[0].boundKey.key
978 2 :
979 2 : // Each level within m.levels may have a set of keys that overlap the
980 2 : // fragmented key span [m.start, m.end). Update m.keys to point to them
981 2 : // and sort them by kind, sequence number. There may not be any keys
982 2 : // spanning [m.start, m.end) if we're between the end of one span and
983 2 : // the start of the next, OR if the configured transform filters any
984 2 : // keys out. We allow empty spans that were emitted by child iterators, but
985 2 : // we elide empty spans created by the mergingIter itself that don't overlap
986 2 : // with any child iterator returned spans (i.e. empty spans that bridge two
987 2 : // distinct child-iterator-defined spans).
988 2 : if found, s, err := m.synthesizeKeys(-1); err != nil {
989 0 : return nil, err
990 2 : } else if found && s != nil {
991 2 : return s, nil
992 2 : }
993 : }
994 : // Exhausted.
995 2 : m.clear()
996 2 : return nil, nil
997 : }
998 :
999 2 : func (m *MergingIter) heapRoot() []byte {
1000 2 : return m.heap.items[0].boundKey.key
1001 2 : }
1002 :
1003 : // synthesizeKeys is called by find{Next,Prev}FragmentSet to populate and
1004 : // sort the set of keys overlapping [m.start, m.end).
1005 : //
1006 : // During forward iteration, if the current heap item is a fragment end,
1007 : // then the fragment's start must be ≤ m.start and the fragment overlaps the
1008 : // current iterator position of [m.start, m.end).
1009 : //
1010 : // During reverse iteration, if the current heap item is a fragment start,
1011 : // then the fragment's end must be ≥ m.end and the fragment overlaps the
1012 : // current iteration position of [m.start, m.end).
1013 : //
1014 : // The boolean return value, `found`, is true if the returned span overlaps
1015 : // with a span returned by a child iterator.
1016 2 : func (m *MergingIter) synthesizeKeys(dir int8) (bool, *keyspan.Span, error) {
1017 2 : if invariants.Enabled {
1018 2 : if m.cmp(m.start, m.end) >= 0 {
1019 0 : panic(fmt.Sprintf("pebble: invariant violation: span start ≥ end: %s >= %s", m.start, m.end))
1020 : }
1021 : }
1022 :
1023 2 : m.keys = m.keys[:0]
1024 2 : found := false
1025 2 : for i := range m.levels {
1026 2 : if dir == +1 && m.levels[i].heapKey.kind == boundKindFragmentEnd ||
1027 2 : dir == -1 && m.levels[i].heapKey.kind == boundKindFragmentStart {
1028 2 : m.keys = append(m.keys, m.levels[i].heapKey.span.Keys...)
1029 2 : found = true
1030 2 : }
1031 : }
1032 : // Sort the keys by sequence number in descending order.
1033 : //
1034 : // TODO(jackson): We should be able to remove this sort and instead
1035 : // guarantee that we'll return keys in the order of the levels they're from.
1036 : // With careful iterator construction, this would guarantee that they're
1037 : // sorted by trailer descending for the range key iteration use case.
1038 2 : slices.SortFunc(m.keys, func(a, b keyspan.Key) int {
1039 2 : return cmp.Compare(b.Trailer, a.Trailer)
1040 2 : })
1041 :
1042 : // Apply the configured transform. See VisibleTransform.
1043 2 : m.span = keyspan.Span{
1044 2 : Start: m.start,
1045 2 : End: m.end,
1046 2 : Keys: m.keys,
1047 2 : KeysOrder: keyspan.ByTrailerDesc,
1048 2 : }
1049 2 : // NB: m.heap.cmp is a base.Compare, whereas m.cmp is a method on
1050 2 : // MergingIter.
1051 2 : if err := m.transformer.Transform(m.heap.cmp, m.span, &m.span); err != nil {
1052 0 : return false, nil, err
1053 0 : }
1054 2 : return found, &m.span, nil
1055 : }
1056 :
1057 2 : func (m *MergingIter) clear() {
1058 2 : for fi := range m.keys {
1059 2 : m.keys[fi] = keyspan.Key{}
1060 2 : }
1061 2 : m.keys = m.keys[:0]
1062 : }
1063 :
1064 : // nextEntry steps to the next entry.
1065 2 : func (m *MergingIter) nextEntry() error {
1066 2 : l := &m.levels[m.heap.items[0].index]
1067 2 : if err := l.next(); err != nil {
1068 1 : return err
1069 1 : }
1070 2 : if !l.heapKey.valid() {
1071 2 : // l.iter is exhausted.
1072 2 : m.heap.pop()
1073 2 : return nil
1074 2 : }
1075 :
1076 2 : if m.heap.len() > 1 {
1077 2 : m.heap.fix(0)
1078 2 : }
1079 2 : return nil
1080 : }
1081 :
1082 : // prevEntry steps to the previous entry.
1083 2 : func (m *MergingIter) prevEntry() error {
1084 2 : l := &m.levels[m.heap.items[0].index]
1085 2 : if err := l.prev(); err != nil {
1086 1 : return err
1087 1 : }
1088 2 : if !l.heapKey.valid() {
1089 2 : // l.iter is exhausted.
1090 2 : m.heap.pop()
1091 2 : return nil
1092 2 : }
1093 :
1094 2 : if m.heap.len() > 1 {
1095 2 : m.heap.fix(0)
1096 2 : }
1097 2 : return nil
1098 : }
1099 :
1100 : // DebugString returns a string representing the current internal state of the
1101 : // merging iterator and its heap for debugging purposes.
1102 0 : func (m *MergingIter) DebugString() string {
1103 0 : var buf bytes.Buffer
1104 0 : fmt.Fprintf(&buf, "Current bounds: [%q, %q)\n", m.start, m.end)
1105 0 : for i := range m.levels {
1106 0 : fmt.Fprintf(&buf, "%d: heap key %s\n", i, m.levels[i].heapKey)
1107 0 : }
1108 0 : return buf.String()
1109 : }
1110 :
1111 : // WrapChildren implements FragmentIterator.
1112 0 : func (m *MergingIter) WrapChildren(wrap keyspan.WrapFn) {
1113 0 : for i := range m.levels {
1114 0 : m.levels[i].iter = wrap(m.levels[i].iter)
1115 0 : }
1116 0 : m.wrapFn = wrap
1117 : }
1118 :
1119 : type mergingIterItem struct {
1120 : // boundKey points to the corresponding mergingIterLevel's `iterKey`.
1121 : *boundKey
1122 : // index is the index of this level within the MergingIter's levels field.
1123 : index int
1124 : }
1125 :
1126 : // mergingIterHeap is copied from mergingIterHeap defined in the root pebble
1127 : // package for use with point keys.
1128 :
1129 : type mergingIterHeap struct {
1130 : cmp base.Compare
1131 : reverse bool
1132 : items []mergingIterItem
1133 : }
1134 :
1135 2 : func (h *mergingIterHeap) len() int {
1136 2 : return len(h.items)
1137 2 : }
1138 :
1139 2 : func (h *mergingIterHeap) less(i, j int) bool {
1140 2 : // This key comparison only uses the user key and not the boundKind. Bound
1141 2 : // kind doesn't matter because when stepping over a user key,
1142 2 : // findNextFragmentSet and findPrevFragmentSet skip past all heap items with
1143 2 : // that user key, and makes no assumptions on ordering. All other heap
1144 2 : // examinations only consider the user key.
1145 2 : ik, jk := h.items[i].key, h.items[j].key
1146 2 : c := h.cmp(ik, jk)
1147 2 : if h.reverse {
1148 2 : return c > 0
1149 2 : }
1150 2 : return c < 0
1151 : }
1152 :
1153 2 : func (h *mergingIterHeap) swap(i, j int) {
1154 2 : h.items[i], h.items[j] = h.items[j], h.items[i]
1155 2 : }
1156 :
1157 : // init, fix, up and down are copied from the go stdlib.
1158 2 : func (h *mergingIterHeap) init() {
1159 2 : // heapify
1160 2 : n := h.len()
1161 2 : for i := n/2 - 1; i >= 0; i-- {
1162 2 : h.down(i, n)
1163 2 : }
1164 : }
1165 :
1166 2 : func (h *mergingIterHeap) fix(i int) {
1167 2 : if !h.down(i, h.len()) {
1168 2 : h.up(i)
1169 2 : }
1170 : }
1171 :
1172 2 : func (h *mergingIterHeap) pop() *mergingIterItem {
1173 2 : n := h.len() - 1
1174 2 : h.swap(0, n)
1175 2 : h.down(0, n)
1176 2 : item := &h.items[n]
1177 2 : h.items = h.items[:n]
1178 2 : return item
1179 2 : }
1180 :
1181 2 : func (h *mergingIterHeap) up(j int) {
1182 2 : for {
1183 2 : i := (j - 1) / 2 // parent
1184 2 : if i == j || !h.less(j, i) {
1185 2 : break
1186 : }
1187 0 : h.swap(i, j)
1188 0 : j = i
1189 : }
1190 : }
1191 :
1192 2 : func (h *mergingIterHeap) down(i0, n int) bool {
1193 2 : i := i0
1194 2 : for {
1195 2 : j1 := 2*i + 1
1196 2 : if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
1197 2 : break
1198 : }
1199 2 : j := j1 // left child
1200 2 : if j2 := j1 + 1; j2 < n && h.less(j2, j1) {
1201 2 : j = j2 // = 2*i + 2 // right child
1202 2 : }
1203 2 : if !h.less(j, i) {
1204 2 : break
1205 : }
1206 2 : h.swap(i, j)
1207 2 : i = j
1208 : }
1209 2 : return i > i0
1210 : }
1211 :
1212 : type boundKind int8
1213 :
1214 : const (
1215 : boundKindInvalid boundKind = iota
1216 : boundKindFragmentStart
1217 : boundKindFragmentEnd
1218 : )
1219 :
1220 : type boundKey struct {
1221 : kind boundKind
1222 : key []byte
1223 : // span holds the span the bound key comes from.
1224 : //
1225 : // If kind is boundKindFragmentStart, then key is span.Start. If kind is
1226 : // boundKindFragmentEnd, then key is span.End.
1227 : span *keyspan.Span
1228 : }
1229 :
1230 2 : func (k boundKey) valid() bool {
1231 2 : return k.kind != boundKindInvalid
1232 2 : }
1233 :
1234 0 : func (k boundKey) String() string {
1235 0 : var buf bytes.Buffer
1236 0 : switch k.kind {
1237 0 : case boundKindInvalid:
1238 0 : fmt.Fprint(&buf, "invalid")
1239 0 : case boundKindFragmentStart:
1240 0 : fmt.Fprint(&buf, "fragment-start")
1241 0 : case boundKindFragmentEnd:
1242 0 : fmt.Fprint(&buf, "fragment-end ")
1243 0 : default:
1244 0 : fmt.Fprintf(&buf, "unknown-kind(%d)", k.kind)
1245 : }
1246 0 : fmt.Fprintf(&buf, " %s [", k.key)
1247 0 : fmt.Fprintf(&buf, "%s", k.span)
1248 0 : fmt.Fprint(&buf, "]")
1249 0 : return buf.String()
1250 : }
1251 :
1252 2 : func firstError(e1, e2 error) error {
1253 2 : if e1 == nil {
1254 2 : return e2
1255 2 : }
1256 1 : return e1
1257 : }
|