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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024-present, fjall-rs
// Copyright (c) 2026-present, Dmitry Prudnikov
use crate::{BoxedIterator, InternalValue, Table, UserKey, version::Run};
use alloc::sync::Arc;
#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, vec::Vec};
use core::ops::{Bound, Deref, RangeBounds};
type OwnedRange = (Bound<UserKey>, Bound<UserKey>);
fn to_owned_range<R: RangeBounds<UserKey>>(range: &R) -> OwnedRange {
(
match range.start_bound() {
Bound::Included(k) => Bound::Included(k.clone()),
Bound::Excluded(k) => Bound::Excluded(k.clone()),
Bound::Unbounded => Bound::Unbounded,
},
match range.end_bound() {
Bound::Included(k) => Bound::Included(k.clone()),
Bound::Excluded(k) => Bound::Excluded(k.clone()),
Bound::Unbounded => Bound::Unbounded,
},
)
}
/// Reads through a disjoint run with lazy reader initialization.
///
/// `lo_reader` and `hi_reader` are constructed on first `next()` /
/// `next_back()` respectively, deferring the `table.range()` seek.
pub struct RunReader {
run: Arc<Run<Table>>,
range: OwnedRange,
lo: usize,
hi: usize,
lo_reader: Option<BoxedIterator<'static>>,
hi_reader: Option<BoxedIterator<'static>>,
lo_initialized: bool,
hi_initialized: bool,
/// Whether, and how, the tables it opens count a scan.
scans: ScanCount,
}
/// How a [`RunReader`] counts a scan on the tables it opens.
enum ScanCount {
/// Not at all: a point read merging operands reads through it too.
Off,
/// On every table it opens.
EachOpen,
/// Once on each table, for a reader repositioned over many ranges as one
/// scan: the tables of the run counted so far.
EachTableOnce(Vec<bool>),
}
impl RunReader {
/// Creates a new `RunReader` using default lexicographic key ordering.
///
/// For trees with a custom [`crate::comparator::UserComparator`], use [`Self::new_cmp`] instead.
#[must_use]
#[cfg_attr(
not(test),
expect(dead_code, reason = "crate-internal API — used by other modules")
)]
pub fn new<R: RangeBounds<UserKey> + Clone + Send + 'static>(
run: Arc<Run<Table>>,
range: R,
) -> Option<Self> {
Self::new_cmp(run, range, &crate::comparator::DefaultUserComparator)
}
/// Like [`Self::new`], but uses a custom comparator for key ordering.
#[must_use]
pub fn new_cmp<R: RangeBounds<UserKey> + Clone + Send + 'static>(
run: Arc<Run<Table>>,
range: R,
cmp: &dyn crate::comparator::UserComparator,
) -> Option<Self> {
assert!(!run.is_empty(), "level reader cannot read empty level");
let (lo, hi) = run.range_overlap_indexes_cmp(&range, cmp)?;
Some(Self::culled(run, range, (Some(lo), Some(hi))))
}
#[must_use]
pub fn culled<R: RangeBounds<UserKey> + Clone + Send + 'static>(
run: Arc<Run<Table>>,
range: R,
(lo, hi): (Option<usize>, Option<usize>),
) -> Self {
let lo = lo.unwrap_or_default();
let hi = hi.unwrap_or(run.len() - 1);
let owned_range = to_owned_range(&range);
Self {
run,
range: owned_range,
lo,
hi,
lo_reader: None,
hi_reader: None,
lo_initialized: false,
hi_initialized: lo >= hi,
scans: ScanCount::Off,
}
}
/// Counts a scan on every table it opens: the reader serves a scan.
#[must_use]
pub(crate) fn counting_scans(mut self) -> Self {
self.scans = ScanCount::EachOpen;
self
}
/// Counts the scan once on each table, however many of the ranges it is
/// repositioned over reach it.
#[must_use]
pub(crate) fn counting_each_table_once(mut self) -> Self {
self.scans = ScanCount::EachTableOnce(alloc::vec![false; self.run.len()]);
self
}
/// Counts the scan on the table at `index`, as the reader counts them.
fn note_scan(&mut self, index: usize) {
match &mut self.scans {
ScanCount::Off => return,
ScanCount::EachOpen => {}
ScanCount::EachTableOnce(scanned) => match scanned.get_mut(index) {
Some(counted) if !*counted => *counted = true,
_ => return,
},
}
if let Some(table) = self.run.get(index) {
table.note_scan();
}
}
/// Re-position this reader to a fresh `range`, reusing the same run `Arc`
/// and struct instead of rebuilding. Recomputes the overlapping table window
/// and drops the boundary readers so they re-open lazily against the new
/// bounds on the next pull.
///
/// When the new range does not overlap the run at all, the reader is left in
/// an immediately-exhausted state (both directions yield `None`).
pub(crate) fn reseek<R: RangeBounds<UserKey> + Clone + Send + 'static>(
&mut self,
range: R,
cmp: &dyn crate::comparator::UserComparator,
) {
self.range = to_owned_range(&range);
self.lo_reader = None;
self.hi_reader = None;
if let Some((lo, hi)) = self.run.range_overlap_indexes_cmp(&range, cmp) {
self.lo = lo;
self.hi = hi;
self.lo_initialized = false;
self.hi_initialized = lo >= hi;
} else {
// No overlap: present as exhausted. Marking both sides initialized
// with no readers makes `next` / `next_back` fall straight through
// to `None` (see their else-branches).
self.lo = 0;
self.hi = 0;
self.lo_initialized = true;
self.hi_initialized = true;
}
}
fn ensure_lo_initialized(&mut self) {
if !self.lo_initialized {
self.note_scan(self.lo);
#[expect(
clippy::expect_used,
reason = "we trust the caller to pass valid indexes"
)]
let lo_table = self.run.deref().get(self.lo).expect("should exist");
self.lo_reader = Some(Box::new(lo_table.range(self.range.clone())));
self.lo_initialized = true;
}
}
fn ensure_hi_initialized(&mut self) {
if !self.hi_initialized {
self.note_scan(self.hi);
#[expect(
clippy::expect_used,
reason = "we trust the caller to pass valid indexes"
)]
let hi_table = self.run.deref().get(self.hi).expect("should exist");
self.hi_reader = Some(Box::new(hi_table.range(self.range.clone())));
self.hi_initialized = true;
}
}
}
impl Iterator for RunReader {
type Item = crate::Result<InternalValue>;
fn next(&mut self) -> Option<Self::Item> {
self.ensure_lo_initialized();
loop {
if let Some(lo_reader) = &mut self.lo_reader {
if let Some(item) = lo_reader.next() {
return Some(item);
}
// NOTE: Lo reader is empty, get next one
self.lo_reader = None;
self.lo += 1;
// Strict `<`: when lo reaches hi, this branch is skipped and
// the hi table is read via ensure_hi_initialized (which uses
// table.range() to respect the range end bound). `.iter()` is
// only used for middle tables that are fully consumed.
if self.lo < self.hi {
self.note_scan(self.lo);
#[expect(
clippy::expect_used,
reason = "hi is at most equal to the last slot; so because 0 <= lo < hi, it must be a valid index"
)]
let table = self.run.get(self.lo).expect("should exist");
self.lo_reader = Some(Box::new(table.iter()));
}
} else {
// Lo exhausted — initialize hi reader if needed and consume from it
self.ensure_hi_initialized();
if let Some(hi_reader) = &mut self.hi_reader {
return hi_reader.next();
}
return None;
}
}
}
}
impl DoubleEndedIterator for RunReader {
fn next_back(&mut self) -> Option<Self::Item> {
self.ensure_hi_initialized();
loop {
if let Some(hi_reader) = &mut self.hi_reader {
if let Some(item) = hi_reader.next_back() {
return Some(item);
}
// NOTE: Hi reader is empty, get prev one
self.hi_reader = None;
self.hi -= 1;
if self.lo < self.hi {
self.note_scan(self.hi);
#[expect(
clippy::expect_used,
reason = "because 0 <= lo <= hi, and hi monotonically decreases, hi must be a valid index"
)]
let table = self.run.get(self.hi).expect("should exist");
self.hi_reader = Some(Box::new(table.iter()));
}
} else {
// Hi exhausted — initialize lo reader if needed and consume from it
self.ensure_lo_initialized();
if let Some(lo_reader) = &mut self.lo_reader {
return lo_reader.next_back();
}
return None;
}
}
}
}
#[cfg(test)]
#[expect(clippy::unwrap_used)]
mod tests;