Skip to main content

arrow_ord/
cmp.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Comparison kernels for `Array`s.
6//!
7//! These kernels can leverage SIMD if available on your system.  Currently no runtime
8//! detection is provided, you should enable the specific SIMD intrinsics using
9//! `RUSTFLAGS="-C target-feature=+avx2"` for example.  See the documentation
10//! [here](https://doc.rust-lang.org/stable/core/arch/) for more information.
11//!
12
13use arrow_array::cast::AsArray;
14use arrow_array::types::{ByteArrayType, ByteViewType};
15use arrow_array::{
16    AnyDictionaryArray, Array, ArrowNativeTypeOp, BooleanArray, Datum, FixedSizeBinaryArray,
17    GenericByteArray, GenericByteViewArray, downcast_primitive_array, downcast_run_array,
18};
19use arrow_buffer::bit_util::ceil;
20use arrow_buffer::{ArrowNativeType, BooleanBuffer, BooleanBufferBuilder, NullBuffer};
21use arrow_schema::{ArrowError, DataType};
22use arrow_select::take::take;
23use std::cmp::Ordering;
24use std::ops::Not;
25
26#[derive(Debug, Copy, Clone)]
27enum Op {
28    Equal,
29    NotEqual,
30    Less,
31    LessEqual,
32    Greater,
33    GreaterEqual,
34    Distinct,
35    NotDistinct,
36}
37
38impl std::fmt::Display for Op {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self {
41            Op::Equal => write!(f, "=="),
42            Op::NotEqual => write!(f, "!="),
43            Op::Less => write!(f, "<"),
44            Op::LessEqual => write!(f, "<="),
45            Op::Greater => write!(f, ">"),
46            Op::GreaterEqual => write!(f, ">="),
47            Op::Distinct => write!(f, "IS DISTINCT FROM"),
48            Op::NotDistinct => write!(f, "IS NOT DISTINCT FROM"),
49        }
50    }
51}
52
53/// Perform `left == right` operation on two [`Datum`].
54///
55/// Comparing null values on either side will yield a null in the corresponding
56/// slot of the resulting [`BooleanArray`].
57///
58/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
59/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
60/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
61/// to treat them as equal, please normalize zeros before calling this kernel. See
62/// [`f32::total_cmp`] and [`f64::total_cmp`].
63///
64/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
65/// For comparisons involving nested types see [`crate::ord::make_comparator`]
66pub fn eq(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
67    compare_op(Op::Equal, lhs, rhs)
68}
69
70/// Perform `left != right` operation on two [`Datum`].
71///
72/// Comparing null values on either side will yield a null in the corresponding
73/// slot of the resulting [`BooleanArray`].
74///
75/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
76/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
77/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
78/// to treat them as equal, please normalize zeros before calling this kernel. See
79/// [`f32::total_cmp`] and [`f64::total_cmp`].
80///
81/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
82/// For comparisons involving nested types see [`crate::ord::make_comparator`]
83pub fn neq(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
84    compare_op(Op::NotEqual, lhs, rhs)
85}
86
87/// Perform `left < right` operation on two [`Datum`].
88///
89/// Comparing null values on either side will yield a null in the corresponding
90/// slot of the resulting [`BooleanArray`].
91///
92/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
93/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
94/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
95/// to treat them as equal, please normalize zeros before calling this kernel. See
96/// [`f32::total_cmp`] and [`f64::total_cmp`].
97///
98/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
99/// For comparisons involving nested types see [`crate::ord::make_comparator`]
100pub fn lt(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
101    compare_op(Op::Less, lhs, rhs)
102}
103
104/// Perform `left <= right` operation on two [`Datum`].
105///
106/// Comparing null values on either side will yield a null in the corresponding
107/// slot of the resulting [`BooleanArray`].
108///
109/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
110/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
111/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
112/// to treat them as equal, please normalize zeros before calling this kernel. See
113/// [`f32::total_cmp`] and [`f64::total_cmp`].
114///
115/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
116/// For comparisons involving nested types see [`crate::ord::make_comparator`]
117pub fn lt_eq(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
118    compare_op(Op::LessEqual, lhs, rhs)
119}
120
121/// Perform `left > right` operation on two [`Datum`].
122///
123/// Comparing null values on either side will yield a null in the corresponding
124/// slot of the resulting [`BooleanArray`].
125///
126/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
127/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
128/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
129/// to treat them as equal, please normalize zeros before calling this kernel. See
130/// [`f32::total_cmp`] and [`f64::total_cmp`].
131///
132/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
133/// For comparisons involving nested types see [`crate::ord::make_comparator`]
134pub fn gt(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
135    compare_op(Op::Greater, lhs, rhs)
136}
137
138/// Perform `left >= right` operation on two [`Datum`].
139///
140/// Comparing null values on either side will yield a null in the corresponding
141/// slot of the resulting [`BooleanArray`].
142///
143/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
144/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
145/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
146/// to treat them as equal, please normalize zeros before calling this kernel. See
147/// [`f32::total_cmp`] and [`f64::total_cmp`].
148///
149/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
150/// For comparisons involving nested types see [`crate::ord::make_comparator`]
151pub fn gt_eq(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
152    compare_op(Op::GreaterEqual, lhs, rhs)
153}
154
155/// Perform `left IS DISTINCT FROM right` operation on two [`Datum`]
156///
157/// [`distinct`] is similar to [`neq`], only differing in null handling. In particular, two
158/// operands are considered DISTINCT if they have a different value or if one of them is NULL
159/// and the other isn't. The result of [`distinct`] is never NULL.
160///
161/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
162/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
163/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
164/// to treat them as equal, please normalize zeros before calling this kernel. See
165/// [`f32::total_cmp`] and [`f64::total_cmp`].
166///
167/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
168/// For comparisons involving nested types see [`crate::ord::make_comparator`]
169pub fn distinct(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
170    compare_op(Op::Distinct, lhs, rhs)
171}
172
173/// Perform `left IS NOT DISTINCT FROM right` operation on two [`Datum`]
174///
175/// [`not_distinct`] is similar to [`eq`], only differing in null handling. In particular, two
176/// operands are considered `NOT DISTINCT` if they have the same value or if both of them
177/// is NULL. The result of [`not_distinct`] is never NULL.
178///
179/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
180/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
181/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
182/// to treat them as equal, please normalize zeros before calling this kernel. See
183/// [`f32::total_cmp`] and [`f64::total_cmp`].
184///
185/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
186/// For comparisons involving nested types see [`crate::ord::make_comparator`]
187pub fn not_distinct(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
188    compare_op(Op::NotDistinct, lhs, rhs)
189}
190
191/// Returns true if `distinct` (via `compare_op`) can handle this data type.
192///
193/// `compare_op` unwraps at most one level of dictionary, then dispatches on
194/// the leaf type. Anything else (REE, nested dictionary, nested/complex types)
195/// must go through `make_comparator` instead.
196pub(crate) fn supports_distinct(dt: &DataType) -> bool {
197    use arrow_schema::DataType::*;
198    let leaf = match dt {
199        Dictionary(_, v) => v.as_ref(),
200        dt => dt,
201    };
202    !leaf.is_nested() && !matches!(leaf, Dictionary(_, _) | RunEndEncoded(_, _))
203}
204
205/// Perform `op` on the provided `Datum`
206#[inline(never)]
207fn compare_op(op: Op, lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
208    use arrow_schema::DataType::*;
209    let (l, l_s) = lhs.get();
210    let (r, r_s) = rhs.get();
211
212    let l_len = l.len();
213    let r_len = r.len();
214
215    if l_len != r_len && !l_s && !r_s {
216        return Err(ArrowError::InvalidArgumentError(format!(
217            "Cannot compare arrays of different lengths, got {l_len} vs {r_len}"
218        )));
219    }
220
221    let len = match l_s {
222        true => r_len,
223        false => l_len,
224    };
225
226    let l_nulls = l.logical_nulls();
227    let r_nulls = r.logical_nulls();
228
229    let l_ree_info = ree_info_opt(l);
230    let l = l_ree_info.as_ref().map(|(vals, _)| *vals).unwrap_or(l);
231
232    let r_ree_info = ree_info_opt(r);
233    let r = r_ree_info.as_ref().map(|(vals, _)| *vals).unwrap_or(r);
234
235    let l_v = l.as_any_dictionary_opt();
236    let l = l_v.map(|x| x.values().as_ref()).unwrap_or(l);
237    let l_t = l.data_type();
238
239    let r_v = r.as_any_dictionary_opt();
240    let r = r_v.map(|x| x.values().as_ref()).unwrap_or(r);
241    let r_t = r.data_type();
242
243    if r_t.is_nested() || l_t.is_nested() {
244        return Err(ArrowError::InvalidArgumentError(format!(
245            "Nested comparison: {l_t} {op} {r_t} (hint: use make_comparator instead)"
246        )));
247    } else if matches!(l_t, Dictionary(_, _) | RunEndEncoded(_, _))
248        || matches!(r_t, Dictionary(_, _) | RunEndEncoded(_, _))
249    {
250        // One dictionary/REE layer is unwrapped above. A leftover dictionary
251        // (nested dict) or REE is not nested according to `DataType::is_nested`,
252        // so without this check `downcast_primitive_array!` panics.
253        return Err(ArrowError::InvalidArgumentError(format!(
254            "Invalid comparison operation: {l_t} {op} {r_t}"
255        )));
256    } else if l_t != r_t {
257        return Err(ArrowError::InvalidArgumentError(format!(
258            "Invalid comparison operation: {l_t} {op} {r_t}"
259        )));
260    }
261
262    // An empty run-end encoded slice reports start run 0 whatever its offset
263    if len == 0 {
264        return Ok(BooleanArray::new(BooleanBuffer::new_unset(0), None));
265    }
266
267    let l_side = SideInfo {
268        is_scalar: l_s,
269        dict: l_v,
270        ree: l_ree_info.as_ref().map(|(_, info)| info),
271    };
272    let r_side = SideInfo {
273        is_scalar: r_s,
274        dict: r_v,
275        ree: r_ree_info.as_ref().map(|(_, info)| info),
276    };
277
278    // Special case: equality against a short scalar that fits the inlined prefix
279    // of a view array, which reduces the comparison to a scan of fixed-width
280    // integers
281    if matches!(op, Op::Equal | Op::NotEqual)
282        && l_side.dict.is_none()
283        && r_side.dict.is_none()
284        && l_side.ree.is_none()
285        && r_side.ree.is_none()
286    {
287        let sides = match (l_s, r_s) {
288            (false, true) => Some((l, r, &l_nulls, &r_nulls)),
289            (true, false) => Some((r, l, &r_nulls, &l_nulls)),
290            _ => None,
291        };
292        // A null constant makes every row null, which this path cannot express
293        if let Some((values, scalar, values_nulls, scalar_nulls)) = sides
294            && scalar_nulls.as_ref().is_none_or(|n| n.null_count() == 0)
295            && let Some(mask) = eq_inline_scalar(values, scalar, l_t, matches!(op, Op::NotEqual))
296        {
297            let nulls = values_nulls.clone().filter(|n| n.null_count() > 0);
298            return Ok(BooleanArray::new(mask, nulls));
299        }
300    }
301
302    // Defer computation as may not be necessary
303    let values = || -> BooleanBuffer {
304        let d = downcast_primitive_array! {
305            (l, r) => apply(op, l.values().as_ref(), &l_side, r.values().as_ref(), &r_side),
306            (Boolean, Boolean) => apply(op, l.as_boolean(), &l_side, r.as_boolean(), &r_side),
307            (Utf8, Utf8) => apply(op, l.as_string::<i32>(), &l_side, r.as_string::<i32>(), &r_side),
308            (Utf8View, Utf8View) => apply(op, l.as_string_view(), &l_side, r.as_string_view(), &r_side),
309            (LargeUtf8, LargeUtf8) => apply(op, l.as_string::<i64>(), &l_side, r.as_string::<i64>(), &r_side),
310            (Binary, Binary) => apply(op, l.as_binary::<i32>(), &l_side, r.as_binary::<i32>(), &r_side),
311            (BinaryView, BinaryView) => apply(op, l.as_binary_view(), &l_side, r.as_binary_view(), &r_side),
312            (LargeBinary, LargeBinary) => apply(op, l.as_binary::<i64>(), &l_side, r.as_binary::<i64>(), &r_side),
313            (FixedSizeBinary(_), FixedSizeBinary(_)) => apply(op, l.as_fixed_size_binary(), &l_side, r.as_fixed_size_binary(), &r_side),
314            (Null, Null) => None,
315            _ => unreachable!(),
316        };
317        d.unwrap_or_else(|| BooleanBuffer::new_unset(len))
318    };
319
320    let l_nulls = l_nulls.filter(|n| n.null_count() > 0);
321    let r_nulls = r_nulls.filter(|n| n.null_count() > 0);
322    Ok(match (l_nulls, l_s, r_nulls, r_s) {
323        (Some(l), true, Some(r), true) | (Some(l), false, Some(r), false) => {
324            // Either both sides are scalar or neither side is scalar
325            match op {
326                Op::Distinct => {
327                    let values = values();
328                    let l = l.inner().bit_chunks().iter_padded();
329                    let r = r.inner().bit_chunks().iter_padded();
330                    let ne = values.bit_chunks().iter_padded();
331
332                    let c = |((l, r), n)| (l ^ r) | (l & r & n);
333                    let buffer = l.zip(r).zip(ne).map(c).collect();
334                    BooleanBuffer::new(buffer, 0, len).into()
335                }
336                Op::NotDistinct => {
337                    let values = values();
338                    let l = l.inner().bit_chunks().iter_padded();
339                    let r = r.inner().bit_chunks().iter_padded();
340                    let e = values.bit_chunks().iter_padded();
341
342                    let c = |((l, r), e)| u64::not(l | r) | (l & r & e);
343                    let buffer = l.zip(r).zip(e).map(c).collect();
344                    BooleanBuffer::new(buffer, 0, len).into()
345                }
346                _ => BooleanArray::new(values(), NullBuffer::union(Some(&l), Some(&r))),
347            }
348        }
349        (Some(_), true, Some(a), false) | (Some(a), false, Some(_), true) => {
350            // Scalar is null, other side is non-scalar and nullable
351            match op {
352                Op::Distinct => a.into_inner().into(),
353                Op::NotDistinct => a.into_inner().not().into(),
354                _ => BooleanArray::new_null(len),
355            }
356        }
357        (Some(nulls), is_scalar, None, _) | (None, _, Some(nulls), is_scalar) => {
358            // Only one side is nullable
359            match is_scalar {
360                true => match op {
361                    // Scalar is null, other side is not nullable
362                    Op::Distinct => BooleanBuffer::new_set(len).into(),
363                    Op::NotDistinct => BooleanBuffer::new_unset(len).into(),
364                    _ => BooleanArray::new_null(len),
365                },
366                false => match op {
367                    Op::Distinct => {
368                        let values = values();
369                        let l = nulls.inner().bit_chunks().iter_padded();
370                        let ne = values.bit_chunks().iter_padded();
371                        let c = |(l, n)| u64::not(l) | n;
372                        let buffer = l.zip(ne).map(c).collect();
373                        BooleanBuffer::new(buffer, 0, len).into()
374                    }
375                    Op::NotDistinct => (nulls.inner() & &values()).into(),
376                    _ => BooleanArray::new(values(), Some(nulls)),
377                },
378            }
379        }
380        // Neither side is nullable
381        (None, _, None, _) => BooleanArray::new(values(), None),
382    })
383}
384
385/// Per-side metadata for a comparison operand.
386struct SideInfo<'a> {
387    is_scalar: bool,
388    dict: Option<&'a dyn AnyDictionaryArray>,
389    ree: Option<&'a ReeInfo<'a>>,
390}
391
392impl SideInfo<'_> {
393    fn has_indirection(&self) -> bool {
394        self.dict.is_some() || self.ree.is_some()
395    }
396}
397
398/// Longest constant whose length and bytes both fit a view's low 64 bits
399const MAX_LOW_HALF_LEN: u32 = 4;
400
401/// Attempts a special case: comparing every value of a byte-view array against a
402/// short constant that fits entirely within a view's inlined prefix
403///
404/// Returns `None` for any other shape, which the caller then handles on the
405/// generic path.
406fn eq_inline_scalar(
407    l: &dyn Array,
408    r: &dyn Array,
409    data_type: &DataType,
410    negate: bool,
411) -> Option<BooleanBuffer> {
412    let (values, needle) = match data_type {
413        DataType::Utf8View => (
414            l.as_string_view().views(),
415            *r.as_string_view().views().first()?,
416        ),
417        DataType::BinaryView => (
418            l.as_binary_view().views(),
419            *r.as_binary_view().views().first()?,
420        ),
421        _ => return None,
422    };
423    // Only a constant whose length and bytes fit the view's low half. Wider
424    // constants need the whole 128-bit view, and comparing that is slower than
425    // the generic path's early exit on a length mismatch.
426    let needle_len = needle as u32;
427    if needle_len > MAX_LOW_HALF_LEN {
428        return None;
429    }
430    let significant = u64::MAX >> (32 - needle_len * 8);
431    let needle = needle as u64 & significant;
432    Some(collect_bool(values.len(), negate, |idx| {
433        let view = unsafe { *values.get_unchecked(idx) };
434        view as u64 & significant == needle
435    }))
436}
437
438/// Perform a potentially vectored `op` on the provided `ArrayOrd`
439fn apply<T: ArrayOrd>(
440    op: Op,
441    l: T,
442    l_info: &SideInfo,
443    r: T,
444    r_info: &SideInfo,
445) -> Option<BooleanBuffer> {
446    if l.len() == 0 || r.len() == 0 {
447        return None; // Handle empty dictionaries
448    }
449
450    if !l_info.is_scalar
451        && !r_info.is_scalar
452        && (l_info.has_indirection() || r_info.has_indirection())
453    {
454        // Both non-scalar with indirection. Pure REE-vs-REE uses segment-based
455        // bulk comparison; other combinations fall back to index vectors.
456        if let (Some(li), None, Some(ri), None) = (l_info.ree, l_info.dict, r_info.ree, r_info.dict)
457        {
458            return Some(apply_ree(op, l, li, r, ri));
459        }
460
461        let l_v = logical_indices(l.len(), l_info.dict, l_info.ree);
462        let r_v = logical_indices(r.len(), r_info.dict, r_info.ree);
463
464        assert_eq!(l_v.len(), r_v.len()); // Sanity check
465
466        Some(match op {
467            Op::Equal | Op::NotDistinct => apply_op_vectored(l, &l_v, r, &r_v, false, T::is_eq),
468            Op::NotEqual | Op::Distinct => apply_op_vectored(l, &l_v, r, &r_v, true, T::is_eq),
469            Op::Less => apply_op_vectored(l, &l_v, r, &r_v, false, T::is_lt),
470            Op::LessEqual => apply_op_vectored(r, &r_v, l, &l_v, true, T::is_lt),
471            Op::Greater => apply_op_vectored(r, &r_v, l, &l_v, false, T::is_lt),
472            Op::GreaterEqual => apply_op_vectored(l, &l_v, r, &r_v, true, T::is_lt),
473        })
474    } else {
475        let l_s = l_info
476            .is_scalar
477            .then(|| scalar_index(l_info.dict, l_info.ree));
478        let r_s = r_info
479            .is_scalar
480            .then(|| scalar_index(r_info.dict, r_info.ree));
481
482        let buffer = match op {
483            Op::Equal | Op::NotDistinct => apply_op(l, l_s, r, r_s, false, T::is_eq),
484            Op::NotEqual | Op::Distinct => apply_op(l, l_s, r, r_s, true, T::is_eq),
485            Op::Less => apply_op(l, l_s, r, r_s, false, T::is_lt),
486            Op::LessEqual => apply_op(r, r_s, l, l_s, true, T::is_lt),
487            Op::Greater => apply_op(r, r_s, l, l_s, false, T::is_lt),
488            Op::GreaterEqual => apply_op(l, l_s, r, r_s, true, T::is_lt),
489        };
490
491        // Expand the physical-length result back to logical length.
492        // Find the non-scalar side that needs expansion (at most one).
493        let side = if l_s.is_none() { l_info } else { r_info };
494        let buffer = match side.dict {
495            Some(d) => take_bits(d, buffer),
496            None => buffer,
497        };
498        Some(match side.ree {
499            Some(info) => expand_from_runs(info, buffer),
500            None => buffer,
501        })
502    }
503}
504
505/// Build a logical→physical index vector for one side of a non-scalar comparison.
506fn logical_indices(
507    len: usize,
508    dict: Option<&dyn AnyDictionaryArray>,
509    ree: Option<&ReeInfo>,
510) -> Vec<usize> {
511    match (dict, ree) {
512        (Some(d), Some(info)) => {
513            let keys = d.normalized_keys();
514            ree_physical_indices(info)
515                .iter()
516                .map(|&i| keys[i])
517                .collect()
518        }
519        (Some(d), None) => d.normalized_keys(),
520        (None, Some(info)) => ree_physical_indices(info),
521        (None, None) => (0..len).collect(),
522    }
523}
524
525fn ree_physical_indices(info: &ReeInfo) -> Vec<usize> {
526    let run_ends = info.run_ends_as_usize();
527    let end = info.offset + info.len;
528    let mut indices = Vec::with_capacity(info.len);
529    let mut pos = info.offset;
530    for (physical, &run_end) in run_ends.iter().enumerate().skip(info.start_physical) {
531        let run_end = run_end.min(end);
532        indices.extend(std::iter::repeat_n(physical, run_end - pos));
533        pos = run_end;
534        if pos >= end {
535            break;
536        }
537    }
538    indices
539}
540
541fn scalar_index(dict: Option<&dyn AnyDictionaryArray>, ree: Option<&ReeInfo>) -> usize {
542    let idx = ree.map(|r| r.start_physical).unwrap_or_default();
543    dict.map(|d| d.normalized_keys()[idx]).unwrap_or(idx)
544}
545
546/// Expand a physical-length BooleanBuffer to logical length by bulk-appending
547/// each run's result. Zero allocation — downcasts internally to access typed
548/// run_ends directly.
549fn expand_from_runs(info: &ReeInfo, buffer: BooleanBuffer) -> BooleanBuffer {
550    let array = info.array;
551    downcast_run_array!(
552        array => {
553            let run_ends = array.run_ends().values();
554            let end = info.offset + info.len;
555            let mut builder = BooleanBufferBuilder::new(info.len);
556            let mut pos = info.offset;
557            for (physical, re) in run_ends.iter().enumerate().skip(info.start_physical) {
558                let run_end = re.as_usize().min(end);
559                // SAFETY: physical < buffer.len() (one entry per run in the values array)
560                builder.append_n(run_end - pos, unsafe { buffer.value_unchecked(physical) });
561                pos = run_end;
562                if pos >= end {
563                    break;
564                }
565            }
566            builder.finish()
567        },
568        _ => unreachable!()
569    )
570}
571
572fn take_bits(v: &dyn AnyDictionaryArray, buffer: BooleanBuffer) -> BooleanBuffer {
573    let array = take(&BooleanArray::new(buffer, None), v.keys(), None).unwrap();
574    array.as_boolean().values().clone()
575}
576
577/// Invokes `f` with values `0..len` collecting the boolean results into a new `BooleanBuffer`
578///
579/// This is similar to [`arrow_buffer::MutableBuffer::collect_bool`] but with
580/// the option to efficiently negate the result
581fn collect_bool(len: usize, neg: bool, f: impl Fn(usize) -> bool) -> BooleanBuffer {
582    let mut buffer = Vec::with_capacity(ceil(len, 64));
583
584    let chunks = len / 64;
585    let remainder = len % 64;
586    buffer.extend((0..chunks).map(|chunk| {
587        let mut packed = 0;
588        for bit_idx in 0..64 {
589            let i = bit_idx + chunk * 64;
590            packed |= (f(i) as u64) << bit_idx;
591        }
592        if neg {
593            packed = !packed
594        }
595
596        packed
597    }));
598
599    if remainder != 0 {
600        let mut packed = 0;
601        for bit_idx in 0..remainder {
602            let i = bit_idx + chunks * 64;
603            packed |= (f(i) as u64) << bit_idx;
604        }
605        if neg {
606            packed = !packed
607        }
608
609        buffer.push(packed);
610    }
611    BooleanBuffer::new(buffer.into(), 0, len)
612}
613
614/// Applies `op` to possibly scalar `ArrayOrd`
615///
616/// If l is scalar `l_s` will be `Some(idx)` where `idx` is the index of the scalar value in `l`
617/// If r is scalar `r_s` will be `Some(idx)` where `idx` is the index of the scalar value in `r`
618///
619/// If `neg` is true the result of `op` will be negated
620fn apply_op<T: ArrayOrd>(
621    l: T,
622    l_s: Option<usize>,
623    r: T,
624    r_s: Option<usize>,
625    neg: bool,
626    op: impl Fn(T::Item, T::Item) -> bool,
627) -> BooleanBuffer {
628    match (l_s, r_s) {
629        (None, None) => {
630            assert_eq!(l.len(), r.len());
631            collect_bool(l.len(), neg, |idx| unsafe {
632                op(l.value_unchecked(idx), r.value_unchecked(idx))
633            })
634        }
635        (Some(l_s), Some(r_s)) => {
636            let a = l.value(l_s);
637            let b = r.value(r_s);
638            std::iter::once(op(a, b) ^ neg).collect()
639        }
640        (Some(l_s), None) => {
641            let v = l.value(l_s);
642            collect_bool(r.len(), neg, |idx| op(v, unsafe { r.value_unchecked(idx) }))
643        }
644        (None, Some(r_s)) => {
645            let v = r.value(r_s);
646            collect_bool(l.len(), neg, |idx| op(unsafe { l.value_unchecked(idx) }, v))
647        }
648    }
649}
650
651/// Applies `op` to possibly scalar `ArrayOrd` with the given indices
652fn apply_op_vectored<T: ArrayOrd>(
653    l: T,
654    l_v: &[usize],
655    r: T,
656    r_v: &[usize],
657    neg: bool,
658    op: impl Fn(T::Item, T::Item) -> bool,
659) -> BooleanBuffer {
660    assert_eq!(l_v.len(), r_v.len());
661    collect_bool(l_v.len(), neg, |idx| unsafe {
662        let l_idx = *l_v.get_unchecked(idx);
663        let r_idx = *r_v.get_unchecked(idx);
664        op(l.value_unchecked(l_idx), r.value_unchecked(r_idx))
665    })
666}
667
668/// Dispatch `op` for a REE-vs-REE comparison (no dictionary on either side)
669/// using segment-based bulk comparison.
670fn apply_ree<T: ArrayOrd>(op: Op, l: T, l_info: &ReeInfo, r: T, r_info: &ReeInfo) -> BooleanBuffer {
671    match op {
672        Op::Equal | Op::NotDistinct => apply_op_ree_segments(l, l_info, r, r_info, false, T::is_eq),
673        Op::NotEqual | Op::Distinct => apply_op_ree_segments(l, l_info, r, r_info, true, T::is_eq),
674        Op::Less => apply_op_ree_segments(l, l_info, r, r_info, false, T::is_lt),
675        Op::LessEqual => apply_op_ree_segments(r, r_info, l, l_info, true, T::is_lt),
676        Op::Greater => apply_op_ree_segments(r, r_info, l, l_info, false, T::is_lt),
677        Op::GreaterEqual => apply_op_ree_segments(l, l_info, r, r_info, true, T::is_lt),
678    }
679}
680
681/// Compare two REE arrays by walking both run_ends simultaneously, comparing
682/// once per aligned segment and bulk-filling the result.
683fn apply_op_ree_segments<T: ArrayOrd>(
684    l: T,
685    l_info: &ReeInfo,
686    r: T,
687    r_info: &ReeInfo,
688    neg: bool,
689    op: fn(T::Item, T::Item) -> bool,
690) -> BooleanBuffer {
691    let l_re = l_info.run_ends_as_usize();
692    let r_re = r_info.run_ends_as_usize();
693    let end = l_info.len;
694    let mut builder = BooleanBufferBuilder::new(l_info.len);
695    let mut l_phys = l_info.start_physical;
696    let mut r_phys = r_info.start_physical;
697    let mut pos = 0usize;
698
699    while pos < end {
700        // SAFETY: l_phys/r_phys are bounded by their respective run counts —
701        // they advance only when pos reaches a run boundary, and pos < end
702        // guarantees we haven't exhausted all runs.
703        // Subtract each side's offset to convert absolute run-ends to logical
704        // coordinates so that arrays with different offsets align correctly.
705        let l_end = (unsafe { *l_re.get_unchecked(l_phys) } - l_info.offset).min(end);
706        let r_end = (unsafe { *r_re.get_unchecked(r_phys) } - r_info.offset).min(end);
707        let seg_end = l_end.min(r_end);
708
709        let result = unsafe { op(l.value_unchecked(l_phys), r.value_unchecked(r_phys)) } ^ neg;
710        builder.append_n(seg_end - pos, result);
711
712        pos = seg_end;
713        if pos >= l_end {
714            l_phys += 1;
715        }
716        if pos >= r_end {
717            r_phys += 1;
718        }
719    }
720
721    builder.finish()
722}
723
724trait ArrayOrd {
725    type Item: Copy;
726
727    fn len(&self) -> usize;
728
729    fn value(&self, idx: usize) -> Self::Item {
730        assert!(idx < self.len());
731        unsafe { self.value_unchecked(idx) }
732    }
733
734    /// # Safety
735    ///
736    /// Safe if `idx < self.len()`
737    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item;
738
739    fn is_eq(l: Self::Item, r: Self::Item) -> bool;
740
741    fn is_lt(l: Self::Item, r: Self::Item) -> bool;
742}
743
744impl ArrayOrd for &BooleanArray {
745    type Item = bool;
746
747    fn len(&self) -> usize {
748        Array::len(self)
749    }
750
751    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item {
752        unsafe { BooleanArray::value_unchecked(self, idx) }
753    }
754
755    fn is_eq(l: Self::Item, r: Self::Item) -> bool {
756        l == r
757    }
758
759    fn is_lt(l: Self::Item, r: Self::Item) -> bool {
760        !l & r
761    }
762}
763
764impl<T: ArrowNativeTypeOp> ArrayOrd for &[T] {
765    type Item = T;
766
767    fn len(&self) -> usize {
768        (*self).len()
769    }
770
771    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item {
772        unsafe { *self.get_unchecked(idx) }
773    }
774
775    fn is_eq(l: Self::Item, r: Self::Item) -> bool {
776        l.is_eq(r)
777    }
778
779    fn is_lt(l: Self::Item, r: Self::Item) -> bool {
780        l.is_lt(r)
781    }
782}
783
784impl<'a, T: ByteArrayType> ArrayOrd for &'a GenericByteArray<T> {
785    type Item = &'a [u8];
786
787    fn len(&self) -> usize {
788        Array::len(self)
789    }
790
791    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item {
792        unsafe { GenericByteArray::value_unchecked(self, idx).as_ref() }
793    }
794
795    fn is_eq(l: Self::Item, r: Self::Item) -> bool {
796        l == r
797    }
798
799    fn is_lt(l: Self::Item, r: Self::Item) -> bool {
800        l < r
801    }
802}
803
804impl<'a, T: ByteViewType> ArrayOrd for &'a GenericByteViewArray<T> {
805    /// This is the item type for the GenericByteViewArray::compare
806    /// Item.0 is the array, Item.1 is the index
807    type Item = (&'a GenericByteViewArray<T>, usize);
808
809    #[inline(always)]
810    fn is_eq(l: Self::Item, r: Self::Item) -> bool {
811        let l_view = unsafe { l.0.views().get_unchecked(l.1) };
812        let r_view = unsafe { r.0.views().get_unchecked(r.1) };
813        if l.0.data_buffers().is_empty() && r.0.data_buffers().is_empty() {
814            // For eq case, we can directly compare the inlined bytes
815            return l_view == r_view;
816        }
817
818        // Fast path for same view (and both inlined)
819        if l_view == r_view && *l_view as u32 <= 12 {
820            return true;
821        }
822
823        let l_len = *l_view as u32;
824        let r_len = *r_view as u32;
825        // Lengths differ
826        if l_len != r_len {
827            return false;
828        }
829
830        // Both are empty
831        if l_len == 0 {
832            return true;
833        }
834
835        // Check prefix
836        if (*l_view >> 32) as u32 != (*r_view >> 32) as u32 {
837            return false;
838        }
839
840        // Both are inlined, and prefixes are equal (so they differ in rest of inlined bytes)
841        if l_len <= 12 {
842            return false;
843        }
844
845        // # Safety
846        // The index is within bounds as it is checked in value()
847        unsafe {
848            let l_buffer_idx = (*l_view >> 64) as u32;
849            let l_offset = (*l_view >> 96) as u32;
850            let r_buffer_idx = (*r_view >> 64) as u32;
851            let r_offset = (*r_view >> 96) as u32;
852
853            let l_data = l.0.data_buffers().get_unchecked(l_buffer_idx as usize);
854            let r_data = r.0.data_buffers().get_unchecked(r_buffer_idx as usize);
855
856            let l_slice = l_data
857                .as_slice()
858                .get_unchecked(l_offset as usize..(l_offset + l_len) as usize);
859            let r_slice = r_data
860                .as_slice()
861                .get_unchecked(r_offset as usize..(r_offset + r_len) as usize);
862            l_slice == r_slice
863        }
864    }
865
866    #[inline(always)]
867    fn is_lt(l: Self::Item, r: Self::Item) -> bool {
868        let l_view = unsafe { l.0.views().get_unchecked(l.1) };
869        let r_view = unsafe { r.0.views().get_unchecked(r.1) };
870
871        if l.0.data_buffers().is_empty() && r.0.data_buffers().is_empty() {
872            // For lt case, we can directly compare the inlined bytes
873            return GenericByteViewArray::<T>::inline_key_fast(*l_view)
874                < GenericByteViewArray::<T>::inline_key_fast(*r_view);
875        }
876
877        if (*l_view as u32) <= 12 && (*r_view as u32) <= 12 {
878            return GenericByteViewArray::<T>::inline_key_fast(*l_view)
879                < GenericByteViewArray::<T>::inline_key_fast(*r_view);
880        }
881
882        let l_prefix = (*l_view >> 32) as u32;
883        let r_prefix = (*r_view >> 32) as u32;
884        if l_prefix != r_prefix {
885            return l_prefix.swap_bytes() < r_prefix.swap_bytes();
886        }
887
888        // Fallback to the generic, unchecked comparison for mixed cases
889        // # Safety
890        // The index is within bounds as it is checked in value()
891        unsafe {
892            let l_data: &[u8] = l.0.value_unchecked(l.1).as_ref();
893            let r_data: &[u8] = r.0.value_unchecked(r.1).as_ref();
894            l_data < r_data
895        }
896    }
897
898    fn len(&self) -> usize {
899        Array::len(self)
900    }
901
902    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item {
903        (self, idx)
904    }
905}
906
907impl<'a> ArrayOrd for &'a FixedSizeBinaryArray {
908    type Item = &'a [u8];
909
910    fn len(&self) -> usize {
911        Array::len(self)
912    }
913
914    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item {
915        unsafe { FixedSizeBinaryArray::value_unchecked(self, idx) }
916    }
917
918    fn is_eq(l: Self::Item, r: Self::Item) -> bool {
919        l == r
920    }
921
922    fn is_lt(l: Self::Item, r: Self::Item) -> bool {
923        l < r
924    }
925}
926
927/// Compares two [`GenericByteViewArray`] at index `left_idx` and `right_idx`
928///
929/// # Panics
930///
931/// Panics if `left_idx >= left.len()` or `right_idx >= right.len()`
932#[inline(always)]
933pub fn compare_byte_view<T: ByteViewType>(
934    left: &GenericByteViewArray<T>,
935    left_idx: usize,
936    right: &GenericByteViewArray<T>,
937    right_idx: usize,
938) -> Ordering {
939    assert!(left_idx < left.len());
940    assert!(right_idx < right.len());
941    if left.data_buffers().is_empty() && right.data_buffers().is_empty() {
942        let l_view = unsafe { left.views().get_unchecked(left_idx) };
943        let r_view = unsafe { right.views().get_unchecked(right_idx) };
944        return GenericByteViewArray::<T>::inline_key_fast(*l_view)
945            .cmp(&GenericByteViewArray::<T>::inline_key_fast(*r_view));
946    }
947    unsafe { GenericByteViewArray::compare_unchecked(left, left_idx, right, right_idx) }
948}
949
950/// Run-end encoding metadata for one side of a comparison. Holds a reference
951/// to the original REE array for deferred typed access to run_ends.
952struct ReeInfo<'a> {
953    array: &'a dyn Array,
954    offset: usize,
955    start_physical: usize,
956    len: usize,
957}
958
959impl ReeInfo<'_> {
960    /// Materialize run_ends as `Vec<usize>`.
961    fn run_ends_as_usize(&self) -> Vec<usize> {
962        let array = self.array;
963        downcast_run_array!(
964            array => array.run_ends().values().iter().map(|v| v.as_usize()).collect(),
965            _ => unreachable!()
966        )
967    }
968}
969
970/// If `array` is RunEndEncoded, return its physical values array and run metadata.
971fn ree_info_opt(array: &dyn Array) -> Option<(&dyn Array, ReeInfo<'_>)> {
972    downcast_run_array!(
973        array => {
974            let run_ends = array.run_ends();
975            let info = ReeInfo {
976                array,
977                offset: run_ends.offset(),
978                start_physical: run_ends.get_start_physical_index(),
979                len: run_ends.len(),
980            };
981            Some((array.values().as_ref(), info))
982        },
983        _ => None
984    )
985}
986
987#[cfg(test)]
988mod tests {
989    use std::sync::Arc;
990
991    use arrow_array::types::Int32Type;
992    use arrow_array::{DictionaryArray, Int32Array, Scalar, StringArray};
993    use arrow_buffer::{Buffer, ScalarBuffer};
994
995    use super::*;
996
997    #[test]
998    fn test_null_dict() {
999        let a = DictionaryArray::new(Int32Array::new_null(10), Arc::new(Int32Array::new_null(0)));
1000        let r = eq(&a, &a).unwrap();
1001        assert_eq!(r.null_count(), 10);
1002
1003        let a = DictionaryArray::new(
1004            Int32Array::from(vec![1, 2, 3, 4, 5, 6]),
1005            Arc::new(Int32Array::new_null(10)),
1006        );
1007        let r = eq(&a, &a).unwrap();
1008        assert_eq!(r.null_count(), 6);
1009
1010        let scalar =
1011            DictionaryArray::new(Int32Array::new_null(1), Arc::new(Int32Array::new_null(0)));
1012        let r = eq(&a, &Scalar::new(&scalar)).unwrap();
1013        assert_eq!(r.null_count(), 6);
1014
1015        let scalar =
1016            DictionaryArray::new(Int32Array::new_null(1), Arc::new(Int32Array::new_null(0)));
1017        let r = eq(&Scalar::new(&scalar), &Scalar::new(&scalar)).unwrap();
1018        assert_eq!(r.null_count(), 1);
1019
1020        let a = DictionaryArray::new(
1021            Int32Array::from(vec![0, 1, 2]),
1022            Arc::new(Int32Array::from(vec![3, 2, 1])),
1023        );
1024        let r = eq(&a, &Scalar::new(&scalar)).unwrap();
1025        assert_eq!(r.null_count(), 3);
1026    }
1027
1028    #[test]
1029    fn is_distinct_from_non_nulls() {
1030        let left_int_array = Int32Array::from(vec![0, 1, 2, 3, 4]);
1031        let right_int_array = Int32Array::from(vec![4, 3, 2, 1, 0]);
1032
1033        assert_eq!(
1034            BooleanArray::from(vec![true, true, false, true, true,]),
1035            distinct(&left_int_array, &right_int_array).unwrap()
1036        );
1037        assert_eq!(
1038            BooleanArray::from(vec![false, false, true, false, false,]),
1039            not_distinct(&left_int_array, &right_int_array).unwrap()
1040        );
1041    }
1042
1043    #[test]
1044    fn is_distinct_from_nulls() {
1045        // [0, 0, NULL, 0, 0, 0]
1046        let left_int_array = Int32Array::new(
1047            vec![0, 0, 1, 3, 0, 0].into(),
1048            Some(NullBuffer::from(vec![true, true, false, true, true, true])),
1049        );
1050        // [0, NULL, NULL, NULL, 0, NULL]
1051        let right_int_array = Int32Array::new(
1052            vec![0; 6].into(),
1053            Some(NullBuffer::from(vec![
1054                true, false, false, false, true, false,
1055            ])),
1056        );
1057
1058        assert_eq!(
1059            BooleanArray::from(vec![false, true, false, true, false, true,]),
1060            distinct(&left_int_array, &right_int_array).unwrap()
1061        );
1062
1063        assert_eq!(
1064            BooleanArray::from(vec![true, false, true, false, true, false,]),
1065            not_distinct(&left_int_array, &right_int_array).unwrap()
1066        );
1067    }
1068
1069    #[test]
1070    fn test_distinct_scalar() {
1071        let a = Int32Array::new_scalar(12);
1072        let b = Int32Array::new_scalar(12);
1073        assert!(!distinct(&a, &b).unwrap().value(0));
1074        assert!(not_distinct(&a, &b).unwrap().value(0));
1075
1076        let a = Int32Array::new_scalar(12);
1077        let b = Int32Array::new_null(1);
1078        assert!(distinct(&a, &b).unwrap().value(0));
1079        assert!(!not_distinct(&a, &b).unwrap().value(0));
1080        assert!(distinct(&b, &a).unwrap().value(0));
1081        assert!(!not_distinct(&b, &a).unwrap().value(0));
1082
1083        let b = Scalar::new(b);
1084        assert!(distinct(&a, &b).unwrap().value(0));
1085        assert!(!not_distinct(&a, &b).unwrap().value(0));
1086
1087        assert!(!distinct(&b, &b).unwrap().value(0));
1088        assert!(not_distinct(&b, &b).unwrap().value(0));
1089
1090        let a = Int32Array::new(
1091            vec![0, 1, 2, 3].into(),
1092            Some(vec![false, false, true, true].into()),
1093        );
1094        let expected = BooleanArray::from(vec![false, false, true, true]);
1095        assert_eq!(distinct(&a, &b).unwrap(), expected);
1096        assert_eq!(distinct(&b, &a).unwrap(), expected);
1097
1098        let expected = BooleanArray::from(vec![true, true, false, false]);
1099        assert_eq!(not_distinct(&a, &b).unwrap(), expected);
1100        assert_eq!(not_distinct(&b, &a).unwrap(), expected);
1101
1102        let b = Int32Array::new_scalar(1);
1103        let expected = BooleanArray::from(vec![true; 4]);
1104        assert_eq!(distinct(&a, &b).unwrap(), expected);
1105        assert_eq!(distinct(&b, &a).unwrap(), expected);
1106        let expected = BooleanArray::from(vec![false; 4]);
1107        assert_eq!(not_distinct(&a, &b).unwrap(), expected);
1108        assert_eq!(not_distinct(&b, &a).unwrap(), expected);
1109
1110        let b = Int32Array::new_scalar(3);
1111        let expected = BooleanArray::from(vec![true, true, true, false]);
1112        assert_eq!(distinct(&a, &b).unwrap(), expected);
1113        assert_eq!(distinct(&b, &a).unwrap(), expected);
1114        let expected = BooleanArray::from(vec![false, false, false, true]);
1115        assert_eq!(not_distinct(&a, &b).unwrap(), expected);
1116        assert_eq!(not_distinct(&b, &a).unwrap(), expected);
1117    }
1118
1119    #[test]
1120    fn test_supports_distinct() {
1121        use arrow_schema::{DataType::*, Field};
1122
1123        assert!(supports_distinct(&Int32));
1124        assert!(supports_distinct(&Float64));
1125        assert!(supports_distinct(&Utf8));
1126        assert!(supports_distinct(&Boolean));
1127
1128        // One level of dictionary unwrap is supported.
1129        assert!(supports_distinct(&Dictionary(
1130            Box::new(Int16),
1131            Box::new(Utf8),
1132        )));
1133
1134        // REE, nested dictionary, and complex types are not supported.
1135        assert!(!supports_distinct(&RunEndEncoded(
1136            Arc::new(Field::new(
1137                Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
1138                Int32,
1139                false
1140            )),
1141            Arc::new(Field::new(
1142                Field::REE_VALUES_FIELD_DEFAULT_NAME,
1143                Int32,
1144                true
1145            )),
1146        )));
1147        assert!(!supports_distinct(&Dictionary(
1148            Box::new(Int16),
1149            Box::new(Dictionary(Box::new(Int8), Box::new(Utf8))),
1150        )));
1151        assert!(!supports_distinct(&List(Arc::new(Field::new(
1152            "item", Int32, true,
1153        )))));
1154        assert!(!supports_distinct(&Struct(
1155            vec![Field::new("a", Int32, true)].into()
1156        )));
1157    }
1158
1159    #[test]
1160    fn test_scalar_negation() {
1161        let a = Int32Array::new_scalar(54);
1162        let b = Int32Array::new_scalar(54);
1163        let r = eq(&a, &b).unwrap();
1164        assert!(r.value(0));
1165
1166        let r = neq(&a, &b).unwrap();
1167        assert!(!r.value(0))
1168    }
1169
1170    #[test]
1171    fn test_scalar_empty() {
1172        let a = Int32Array::new_null(0);
1173        let b = Int32Array::new_scalar(23);
1174        let r = eq(&a, &b).unwrap();
1175        assert_eq!(r.len(), 0);
1176        let r = eq(&b, &a).unwrap();
1177        assert_eq!(r.len(), 0);
1178    }
1179
1180    #[test]
1181    fn test_dictionary_nulls() {
1182        let values = StringArray::from(vec![Some("us-west"), Some("us-east")]);
1183        let nulls = NullBuffer::from(vec![false, true, true]);
1184
1185        let key_values = vec![100i32, 1i32, 0i32].into();
1186        let keys = Int32Array::new(key_values, Some(nulls));
1187        let col = DictionaryArray::try_new(keys, Arc::new(values)).unwrap();
1188
1189        neq(&col.slice(0, col.len() - 1), &col.slice(1, col.len() - 1)).unwrap();
1190    }
1191
1192    #[test]
1193    fn test_nested_dictionary_eq_returns_error() {
1194        let inner = DictionaryArray::new(
1195            Int32Array::from(vec![0, 1]),
1196            Arc::new(StringArray::from(vec!["a", "b"])),
1197        );
1198        let outer = DictionaryArray::new(Int32Array::from(vec![0, 1]), Arc::new(inner));
1199        let err = eq(&outer, &outer).expect_err("nested dictionary must not panic");
1200        assert!(
1201            matches!(err, ArrowError::InvalidArgumentError(_)),
1202            "unexpected error: {err}"
1203        );
1204    }
1205
1206    #[test]
1207    fn test_string_view_mixed_lt() {
1208        let a = arrow_array::StringViewArray::from(vec![
1209            Some("apple"),
1210            Some("apple"),
1211            Some("apple_long_string"),
1212        ]);
1213        let b = arrow_array::StringViewArray::from(vec![
1214            Some("apple_long_string"),
1215            Some("appl"),
1216            Some("apple"),
1217        ]);
1218        // "apple" < "apple_long_string" -> true
1219        // "apple" < "appl" -> false
1220        // "apple_long_string" < "apple" -> false
1221        assert_eq!(
1222            lt(&a, &b).unwrap(),
1223            BooleanArray::from(vec![true, false, false])
1224        );
1225    }
1226
1227    /// A null constant makes every row null, whatever the values are
1228    #[test]
1229    fn test_byte_view_eq_null_scalar() {
1230        let a = arrow_array::StringViewArray::from(vec![Some(""), Some("x"), None]);
1231        let scalar = arrow_array::StringViewArray::new_null(1);
1232
1233        let r = neq(&a, &Scalar::new(&scalar)).unwrap();
1234
1235        assert_eq!(r.null_count(), 3);
1236    }
1237
1238    /// A null row's view is arbitrary, so validity decides, not bytes
1239    #[test]
1240    fn test_byte_view_eq_null_row() {
1241        let a = arrow_array::StringViewArray::from(vec![Some(""), Some("x"), None]);
1242        let scalar = arrow_array::StringViewArray::from(vec![""]);
1243
1244        let r = neq(&a, &Scalar::new(&scalar)).unwrap();
1245
1246        assert!(!r.value(0));
1247        assert!(r.value(1));
1248        assert!(r.is_null(2));
1249    }
1250
1251    /// The constant may sit on either side; equality is symmetric
1252    #[test]
1253    fn test_byte_view_eq_scalar_either_side() {
1254        let a =
1255            arrow_array::StringViewArray::from(vec![Some(""), Some("xxxx"), Some("xxxxxxxxxxxxx")]);
1256        let scalar = Scalar::new(arrow_array::StringViewArray::from(vec!["xxxx"]));
1257
1258        assert_eq!(eq(&a, &scalar).unwrap(), eq(&scalar, &a).unwrap());
1259        assert_eq!(eq(&a, &scalar).unwrap().true_count(), 1);
1260    }
1261
1262    #[test]
1263    fn test_string_view_eq() {
1264        let a = arrow_array::StringViewArray::from(vec![
1265            Some("hello"),
1266            Some("world"),
1267            None,
1268            Some("very long string exceeding 12 bytes"),
1269        ]);
1270        let b = arrow_array::StringViewArray::from(vec![
1271            Some("hello"),
1272            Some("world"),
1273            None,
1274            Some("very long string exceeding 12 bytes"),
1275        ]);
1276        assert_eq!(
1277            eq(&a, &b).unwrap(),
1278            BooleanArray::from(vec![Some(true), Some(true), None, Some(true)])
1279        );
1280
1281        let c = arrow_array::StringViewArray::from(vec![
1282            Some("hello"),
1283            Some("world!"),
1284            None,
1285            Some("very long string exceeding 12 bytes!"),
1286        ]);
1287        assert_eq!(
1288            eq(&a, &c).unwrap(),
1289            BooleanArray::from(vec![Some(true), Some(false), None, Some(false)])
1290        );
1291    }
1292
1293    #[test]
1294    fn test_string_view_lt() {
1295        let a = arrow_array::StringViewArray::from(vec![
1296            Some("apple"),
1297            Some("banana"),
1298            Some("very long apple exceeding 12 bytes"),
1299            Some("very long banana exceeding 12 bytes"),
1300        ]);
1301        let b = arrow_array::StringViewArray::from(vec![
1302            Some("banana"),
1303            Some("apple"),
1304            Some("very long banana exceeding 12 bytes"),
1305            Some("very long apple exceeding 12 bytes"),
1306        ]);
1307        assert_eq!(
1308            lt(&a, &b).unwrap(),
1309            BooleanArray::from(vec![true, false, true, false])
1310        );
1311    }
1312
1313    #[test]
1314    fn test_string_view_eq_prefix_mismatch() {
1315        // Prefix mismatch should short-circuit equality for long values.
1316        let a =
1317            arrow_array::StringViewArray::from(vec![Some("very long apple exceeding 12 bytes")]);
1318        let b =
1319            arrow_array::StringViewArray::from(vec![Some("very long banana exceeding 12 bytes")]);
1320        assert_eq!(eq(&a, &b).unwrap(), BooleanArray::from(vec![Some(false)]));
1321    }
1322
1323    #[test]
1324    fn test_string_view_lt_prefix_mismatch() {
1325        // Prefix mismatch should decide ordering without full compare for long values.
1326        let a =
1327            arrow_array::StringViewArray::from(vec![Some("apple long string exceeding 12 bytes")]);
1328        let b =
1329            arrow_array::StringViewArray::from(vec![Some("banana long string exceeding 12 bytes")]);
1330        assert_eq!(lt(&a, &b).unwrap(), BooleanArray::from(vec![true]));
1331    }
1332
1333    #[test]
1334    fn test_string_view_eq_inline_fast_path() {
1335        // Inline-only arrays should compare by view equality fast path.
1336        let a = arrow_array::StringViewArray::from(vec![Some("ab")]);
1337        let b = arrow_array::StringViewArray::from(vec![Some("ab")]);
1338        assert!(!has_buffers(&a));
1339        assert!(!has_buffers(&b));
1340        assert_eq!(eq(&a, &b).unwrap(), BooleanArray::from(vec![Some(true)]));
1341    }
1342
1343    #[test]
1344    fn test_string_view_eq_inline_prefix_mismatch_with_buffers() {
1345        // Non-empty buffers force the prefix mismatch branch for inline values.
1346        let a = arrow_array::StringViewArray::from(vec![
1347            Some("ab"),
1348            Some("long string to allocate buffers"),
1349        ]);
1350        let b = arrow_array::StringViewArray::from(vec![
1351            Some("ac"),
1352            Some("long string to allocate buffers"),
1353        ]);
1354        assert!(has_buffers(&a));
1355        assert!(has_buffers(&b));
1356        assert_eq!(
1357            eq(&a, &b).unwrap(),
1358            BooleanArray::from(vec![Some(false), Some(true)])
1359        );
1360    }
1361
1362    #[test]
1363    fn test_string_view_eq_empty_len_branch() {
1364        // Reach the zero-length branch by bypassing the inline fast path with a dummy buffer.
1365        let raw_a = 0u128;
1366        let raw_b = 1u128 << 96;
1367        let views_a = ScalarBuffer::from(vec![raw_a]);
1368        let views_b = ScalarBuffer::from(vec![raw_b]);
1369        let buffers: Arc<[Buffer]> = Arc::from([Buffer::from_slice_ref([0u8])]);
1370        let a =
1371            unsafe { arrow_array::StringViewArray::new_unchecked(views_a, buffers.clone(), None) };
1372        let b = unsafe { arrow_array::StringViewArray::new_unchecked(views_b, buffers, None) };
1373        assert!(has_buffers(&a));
1374        assert!(has_buffers(&b));
1375        assert!(<&arrow_array::StringViewArray as ArrayOrd>::is_eq(
1376            (&a, 0),
1377            (&b, 0)
1378        ));
1379    }
1380
1381    #[test]
1382    fn test_string_view_long_prefix_mismatch_array_ord() {
1383        // Long strings with differing prefixes should short-circuit on prefix ordering.
1384        let a =
1385            arrow_array::StringViewArray::from(vec![Some("apple long string exceeding 12 bytes")]);
1386        let b =
1387            arrow_array::StringViewArray::from(vec![Some("banana long string exceeding 12 bytes")]);
1388        assert!(has_buffers(&a));
1389        assert!(has_buffers(&b));
1390        assert!(<&arrow_array::StringViewArray as ArrayOrd>::is_lt(
1391            (&a, 0),
1392            (&b, 0)
1393        ));
1394    }
1395
1396    #[test]
1397    fn test_string_view_inline_mismatch_array_ord() {
1398        // Long strings with differing prefixes should short-circuit on prefix ordering.
1399        let a = arrow_array::StringViewArray::from(vec![Some("ap")]);
1400        let b = arrow_array::StringViewArray::from(vec![Some("ba")]);
1401        assert!(!has_buffers(&a));
1402        assert!(!has_buffers(&b));
1403        assert!(<&arrow_array::StringViewArray as ArrayOrd>::is_lt(
1404            (&a, 0),
1405            (&b, 0)
1406        ));
1407    }
1408    #[test]
1409    fn test_compare_byte_view_inline_fast_path() {
1410        // Inline-only views should compare via inline key in compare_byte_view.
1411        let a = arrow_array::StringViewArray::from(vec![Some("ab")]);
1412        let b = arrow_array::StringViewArray::from(vec![Some("ac")]);
1413        assert!(!has_buffers(&a));
1414        assert!(!has_buffers(&b));
1415        assert_eq!(compare_byte_view(&a, 0, &b, 0), Ordering::Less);
1416    }
1417
1418    fn has_buffers<T: ByteViewType>(array: &GenericByteViewArray<T>) -> bool {
1419        !array.data_buffers().is_empty()
1420    }
1421
1422    fn ree_str(runs: &[(Option<&str>, i32)]) -> arrow_array::RunArray<Int32Type> {
1423        let mut ends = Vec::new();
1424        let mut vals = Vec::new();
1425        let mut end = 0i32;
1426        for &(v, n) in runs {
1427            end += n;
1428            ends.push(end);
1429            vals.push(v);
1430        }
1431        arrow_array::RunArray::try_new(&Int32Array::from(ends), &StringArray::from(vals)).unwrap()
1432    }
1433
1434    #[test]
1435    fn test_ree_scalar() {
1436        let a = ree_str(&[(Some("a"), 3), (Some("b"), 2)]);
1437
1438        let s = Scalar::new(StringArray::from(vec!["b"]));
1439        assert_eq!(
1440            eq(&a, &s).unwrap(),
1441            BooleanArray::from(vec![false, false, false, true, true])
1442        );
1443        assert_eq!(
1444            neq(&a, &s).unwrap(),
1445            BooleanArray::from(vec![true, true, true, false, false])
1446        );
1447        assert_eq!(
1448            lt(&a, &s).unwrap(),
1449            BooleanArray::from(vec![true, true, true, false, false])
1450        );
1451        assert_eq!(lt_eq(&a, &s).unwrap(), BooleanArray::from(vec![true; 5]));
1452        assert_eq!(gt(&a, &s).unwrap(), BooleanArray::from(vec![false; 5]));
1453        assert_eq!(
1454            gt_eq(&a, &s).unwrap(),
1455            BooleanArray::from(vec![false, false, false, true, true])
1456        );
1457
1458        // Scalar on left side
1459        let scalar = Scalar::new(ree_str(&[(Some("a"), 1)]));
1460        assert_eq!(
1461            eq(&scalar, &a).unwrap(),
1462            BooleanArray::from(vec![true, true, true, false, false])
1463        );
1464        assert_eq!(
1465            lt_eq(&scalar, &a).unwrap(),
1466            BooleanArray::from(vec![true; 5])
1467        );
1468
1469        // REE-wrapped scalar (DataFusion's ScalarValue::RunEndEncoded)
1470        assert_eq!(
1471            eq(&a, &Scalar::new(ree_str(&[(Some("a"), 1)]))).unwrap(),
1472            BooleanArray::from(vec![true, true, true, false, false]),
1473        );
1474
1475        // Single run
1476        let a = ree_str(&[(Some("x"), 100)]);
1477        let r = eq(&a, &Scalar::new(StringArray::from(vec!["x"]))).unwrap();
1478        assert_eq!(r.true_count(), 100);
1479    }
1480
1481    #[test]
1482    fn test_ree_ree() {
1483        // Different run boundaries, all ops.
1484        let a = ree_str(&[(Some("a"), 3), (Some("b"), 2)]);
1485        let b = ree_str(&[(Some("a"), 2), (Some("b"), 3)]);
1486        // a=[a,a,a,b,b] vs b=[a,a,b,b,b]
1487        assert_eq!(
1488            eq(&a, &b).unwrap(),
1489            BooleanArray::from(vec![true, true, false, true, true])
1490        );
1491        assert_eq!(
1492            neq(&a, &b).unwrap(),
1493            BooleanArray::from(vec![false, false, true, false, false])
1494        );
1495        assert_eq!(
1496            lt(&a, &b).unwrap(),
1497            BooleanArray::from(vec![false, false, true, false, false])
1498        );
1499        assert_eq!(
1500            gt_eq(&a, &b).unwrap(),
1501            BooleanArray::from(vec![true, true, false, true, true])
1502        );
1503    }
1504
1505    #[test]
1506    fn test_ree_sliced() {
1507        // Scalar with sliced REE
1508        let a = ree_str(&[(Some("a"), 3), (Some("b"), 2)]).slice(2, 3);
1509        let s = Scalar::new(StringArray::from(vec!["b"]));
1510        assert_eq!(
1511            eq(&a, &s).unwrap(),
1512            BooleanArray::from(vec![false, true, true])
1513        );
1514
1515        // Both sides sliced, REE vs REE
1516        let a = ree_str(&[(Some("a"), 3), (Some("b"), 2)]).slice(1, 4);
1517        let b = ree_str(&[(Some("a"), 2), (Some("b"), 3)]).slice(1, 4);
1518        assert_eq!(
1519            eq(&a, &b).unwrap(),
1520            BooleanArray::from(vec![true, false, true, true])
1521        );
1522    }
1523
1524    #[test]
1525    fn test_ree_sliced_different_offsets() {
1526        // left expands to ["a", "a", "b", "b"]
1527        let a = ree_str(&[(Some("a"), 3), (Some("b"), 2)]).slice(1, 4);
1528        // right expands to ["a", "a", "b", "b"]
1529        let b = ree_str(&[(Some("a"), 2), (Some("b"), 3)]).slice(0, 4);
1530        assert_eq!(
1531            eq(&a, &b).unwrap(),
1532            BooleanArray::from(vec![true, true, true, true])
1533        );
1534    }
1535
1536    #[test]
1537    fn test_ree_nullable() {
1538        let a = ree_str(&[(Some("a"), 2), (None, 1), (Some("b"), 2)]);
1539
1540        // Scalar: null-aware ops
1541        let s = Scalar::new(StringArray::from(vec!["a"]));
1542        assert_eq!(
1543            not_distinct(&a, &s).unwrap(),
1544            BooleanArray::from(vec![true, true, false, false, false])
1545        );
1546        assert_eq!(
1547            distinct(&a, &s).unwrap(),
1548            BooleanArray::from(vec![false, false, true, true, true])
1549        );
1550
1551        // REE vs REE with nulls
1552        let b = ree_str(&[(Some("a"), 3), (None, 2)]);
1553        assert_eq!(
1554            eq(&a, &b).unwrap(),
1555            BooleanArray::from(vec![Some(true), Some(true), None, None, None])
1556        );
1557    }
1558
1559    #[test]
1560    fn test_ree_mixed() {
1561        let a = ree_str(&[(Some("a"), 3), (Some("b"), 2)]);
1562
1563        // REE vs plain array
1564        let b = StringArray::from(vec!["a", "a", "b", "b", "b"]);
1565        assert_eq!(
1566            eq(&a, &b).unwrap(),
1567            BooleanArray::from(vec![true, true, false, true, true])
1568        );
1569
1570        // REE wrapping a DictionaryArray
1571        let dict = DictionaryArray::new(
1572            Int32Array::from(vec![1, 0]),
1573            Arc::new(StringArray::from(vec!["x", "y"])),
1574        );
1575        let ree_dict =
1576            arrow_array::RunArray::try_new(&Int32Array::from(vec![3, 5]), &dict).unwrap();
1577        let s = Scalar::new(StringArray::from(vec!["y"]));
1578        assert_eq!(
1579            eq(&ree_dict, &s).unwrap(),
1580            BooleanArray::from(vec![true, true, true, false, false])
1581        );
1582
1583        // Numeric REE (Int32 values)
1584        let ree_int = arrow_array::RunArray::try_new(
1585            &Int32Array::from(vec![3, 5]),
1586            &Int32Array::from(vec![10, 20]),
1587        )
1588        .unwrap();
1589        assert_eq!(
1590            eq(&ree_int, &Scalar::new(Int32Array::from(vec![10]))).unwrap(),
1591            BooleanArray::from(vec![true, true, true, false, false])
1592        );
1593
1594        // Empty REE
1595        let empty_a = ree_str(&[(Some("a"), 1)]).slice(0, 0);
1596        let empty_b = ree_str(&[(Some("b"), 1)]).slice(0, 0);
1597        assert_eq!(eq(&empty_a, &empty_b).unwrap().len(), 0);
1598
1599        // Empty REE sliced past the first run
1600        let empty_a = ree_str(&[(Some("a"), 1), (Some("b"), 1)]).slice(2, 0);
1601        let empty_b = ree_str(&[(Some("a"), 2)]).slice(2, 0);
1602        let s = Scalar::new(StringArray::from(vec!["a"]));
1603        assert_eq!(eq(&empty_a, &s).unwrap().len(), 0);
1604        assert_eq!(eq(&empty_a, &empty_b).unwrap().len(), 0);
1605    }
1606
1607    #[test]
1608    fn test_compare_byte_view() {
1609        let a = arrow_array::StringViewArray::from(vec![
1610            Some("apple"),
1611            Some("banana"),
1612            Some("very long apple exceeding 12 bytes"),
1613            Some("very long banana exceeding 12 bytes"),
1614        ]);
1615        let b = arrow_array::StringViewArray::from(vec![
1616            Some("apple"),
1617            Some("apple"),
1618            Some("very long apple exceeding 12 bytes"),
1619            Some("very long apple exceeding 12 bytes"),
1620        ]);
1621
1622        assert_eq!(compare_byte_view(&a, 0, &b, 0), Ordering::Equal);
1623        assert_eq!(compare_byte_view(&a, 1, &b, 1), Ordering::Greater);
1624        assert_eq!(compare_byte_view(&a, 2, &b, 2), Ordering::Equal);
1625        assert_eq!(compare_byte_view(&a, 3, &b, 3), Ordering::Greater);
1626    }
1627}