use super::run::Ranged;
use crate::comparator::UserComparator;
use crate::version::Run;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
pub fn optimize_runs<T: Clone + Ranged>(
runs: Vec<Run<T>>,
cmp: &dyn UserComparator,
) -> Vec<Run<T>> {
if runs.len() <= 1 {
runs
} else {
let mut new_runs: Vec<Run<T>> = Vec::new();
for run in &runs {
for table in run.iter() {
let last_overlap = new_runs.iter().rposition(|existing_run| {
existing_run.iter().any(|x| {
table
.key_range()
.overlaps_with_key_range_cmp(x.key_range(), cmp)
})
});
let target = match last_overlap {
Some(idx) => new_runs.get_mut(idx + 1),
None => new_runs.first_mut(),
};
if let Some(target) = target {
target.push_cmp(table.clone(), cmp);
} else {
#[expect(
clippy::expect_used,
reason = "we pass in a table, so the run cannot be None"
)]
new_runs.push(Run::new(vec![table.clone()]).expect("run should not be empty"));
}
}
}
new_runs
}
}
#[cfg(test)]
#[expect(clippy::unwrap_used)]
mod tests;