use std::cmp::Ordering;
use arrow::array::{Array, RecordBatch};
use arrow::compute::concat_batches;
use arrow_schema::SortOptions;
use datafusion_common::{Result, internal_err};
use datafusion_expr::{JoinType, Operator};
pub(super) fn non_null_range(values: &dyn Array, options: SortOptions) -> (usize, usize) {
let null_count = values.logical_null_count();
if options.nulls_first {
(null_count, values.len())
} else {
(0, values.len() - null_count)
}
}
pub(super) fn unmatched_buffered_batch(
batch: &RecordBatch,
min_marked: usize,
non_null_end: usize,
) -> Result<RecordBatch> {
let prefix = batch.slice(0, min_marked.min(non_null_end));
if non_null_end == batch.num_rows() {
return Ok(prefix);
}
let nulls = batch.slice(non_null_end, batch.num_rows() - non_null_end);
Ok(concat_batches(&batch.schema(), [&prefix, &nulls])?)
}
pub(super) fn is_right_existence_join(join_type: JoinType) -> bool {
matches!(
join_type,
JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark
)
}
pub(super) fn need_produce_result_in_final(join_type: JoinType) -> bool {
matches!(join_type, JoinType::Full | JoinType::Left)
}
pub(super) fn matches_on_equal(operator: Operator) -> Result<bool> {
match operator {
Operator::Lt | Operator::Gt => Ok(false),
Operator::LtEq | Operator::GtEq => Ok(true),
_ => internal_err!("PiecewiseMergeJoin should not contain operator, {operator}"),
}
}
pub(super) fn is_match(ordering: Ordering, match_on_equal: bool) -> bool {
match ordering {
Ordering::Less => true,
Ordering::Equal => match_on_equal,
Ordering::Greater => false,
}
}
pub(super) fn first_match(
lo: usize,
hi: usize,
matches: impl Fn(usize) -> bool,
) -> usize {
let (mut first, mut above) = (lo, hi);
while first < above {
let mid = first + (above - first) / 2;
if matches(mid) {
above = mid;
} else {
first = mid + 1;
}
}
first
}
#[cfg(test)]
mod tests {
use super::first_match;
#[test]
fn first_match_agrees_with_linear_scan() {
for hi in 0..=40usize {
for boundary in 0..=hi {
for lo in 0..=hi {
let probes = std::cell::Cell::new(0usize);
let matches = |idx: usize| {
assert!(
idx >= lo && idx < hi,
"probed {idx} outside [{lo}, {hi})"
);
probes.set(probes.get() + 1);
idx >= boundary
};
let expected = (lo..hi).find(|&idx| idx >= boundary).unwrap_or(hi);
assert_eq!(
first_match(lo, hi, matches),
expected,
"hi={hi} boundary={boundary} lo={lo}"
);
let bound = (usize::BITS - (hi - lo).leading_zeros()) as usize;
assert!(
probes.get() <= bound,
"hi={hi} boundary={boundary} lo={lo}: {} probes > {bound}",
probes.get()
);
}
}
}
}
}