arrow_ord/
cmp.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Comparison kernels for `Array`s.
19//!
20//! These kernels can leverage SIMD if available on your system.  Currently no runtime
21//! detection is provided, you should enable the specific SIMD intrinsics using
22//! `RUSTFLAGS="-C target-feature=+avx2"` for example.  See the documentation
23//! [here](https://doc.rust-lang.org/stable/core/arch/) for more information.
24//!
25
26use arrow_array::cast::AsArray;
27use arrow_array::types::{ByteArrayType, ByteViewType};
28use arrow_array::{
29    AnyDictionaryArray, Array, ArrowNativeTypeOp, BooleanArray, Datum, FixedSizeBinaryArray,
30    GenericByteArray, GenericByteViewArray, downcast_primitive_array,
31};
32use arrow_buffer::bit_util::ceil;
33use arrow_buffer::{BooleanBuffer, NullBuffer};
34use arrow_schema::ArrowError;
35use arrow_select::take::take;
36use std::cmp::Ordering;
37use std::ops::Not;
38
39#[derive(Debug, Copy, Clone)]
40enum Op {
41    Equal,
42    NotEqual,
43    Less,
44    LessEqual,
45    Greater,
46    GreaterEqual,
47    Distinct,
48    NotDistinct,
49}
50
51impl std::fmt::Display for Op {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        match self {
54            Op::Equal => write!(f, "=="),
55            Op::NotEqual => write!(f, "!="),
56            Op::Less => write!(f, "<"),
57            Op::LessEqual => write!(f, "<="),
58            Op::Greater => write!(f, ">"),
59            Op::GreaterEqual => write!(f, ">="),
60            Op::Distinct => write!(f, "IS DISTINCT FROM"),
61            Op::NotDistinct => write!(f, "IS NOT DISTINCT FROM"),
62        }
63    }
64}
65
66/// Perform `left == right` operation on two [`Datum`].
67///
68/// Comparing null values on either side will yield a null in the corresponding
69/// slot of the resulting [`BooleanArray`].
70///
71/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
72/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
73/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
74/// to treat them as equal, please normalize zeros before calling this kernel. See
75/// [`f32::total_cmp`] and [`f64::total_cmp`].
76///
77/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
78/// For comparisons involving nested types see [`crate::ord::make_comparator`]
79pub fn eq(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
80    compare_op(Op::Equal, lhs, rhs)
81}
82
83/// Perform `left != right` operation on two [`Datum`].
84///
85/// Comparing null values on either side will yield a null in the corresponding
86/// slot of the resulting [`BooleanArray`].
87///
88/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
89/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
90/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
91/// to treat them as equal, please normalize zeros before calling this kernel. See
92/// [`f32::total_cmp`] and [`f64::total_cmp`].
93///
94/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
95/// For comparisons involving nested types see [`crate::ord::make_comparator`]
96pub fn neq(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
97    compare_op(Op::NotEqual, lhs, rhs)
98}
99
100/// Perform `left < right` operation on two [`Datum`].
101///
102/// Comparing null values on either side will yield a null in the corresponding
103/// slot of the resulting [`BooleanArray`].
104///
105/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
106/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
107/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
108/// to treat them as equal, please normalize zeros before calling this kernel. See
109/// [`f32::total_cmp`] and [`f64::total_cmp`].
110///
111/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
112/// For comparisons involving nested types see [`crate::ord::make_comparator`]
113pub fn lt(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
114    compare_op(Op::Less, lhs, rhs)
115}
116
117/// Perform `left <= right` operation on two [`Datum`].
118///
119/// Comparing null values on either side will yield a null in the corresponding
120/// slot of the resulting [`BooleanArray`].
121///
122/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
123/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
124/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
125/// to treat them as equal, please normalize zeros before calling this kernel. See
126/// [`f32::total_cmp`] and [`f64::total_cmp`].
127///
128/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
129/// For comparisons involving nested types see [`crate::ord::make_comparator`]
130pub fn lt_eq(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
131    compare_op(Op::LessEqual, lhs, rhs)
132}
133
134/// Perform `left > right` operation on two [`Datum`].
135///
136/// Comparing null values on either side will yield a null in the corresponding
137/// slot of the resulting [`BooleanArray`].
138///
139/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
140/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
141/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
142/// to treat them as equal, please normalize zeros before calling this kernel. See
143/// [`f32::total_cmp`] and [`f64::total_cmp`].
144///
145/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
146/// For comparisons involving nested types see [`crate::ord::make_comparator`]
147pub fn gt(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
148    compare_op(Op::Greater, lhs, rhs)
149}
150
151/// Perform `left >= right` operation on two [`Datum`].
152///
153/// Comparing null values on either side will yield a null in the corresponding
154/// slot of the resulting [`BooleanArray`].
155///
156/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
157/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
158/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
159/// to treat them as equal, please normalize zeros before calling this kernel. See
160/// [`f32::total_cmp`] and [`f64::total_cmp`].
161///
162/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
163/// For comparisons involving nested types see [`crate::ord::make_comparator`]
164pub fn gt_eq(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
165    compare_op(Op::GreaterEqual, lhs, rhs)
166}
167
168/// Perform `left IS DISTINCT FROM right` operation on two [`Datum`]
169///
170/// [`distinct`] is similar to [`neq`], only differing in null handling. In particular, two
171/// operands are considered DISTINCT if they have a different value or if one of them is NULL
172/// and the other isn't. The result of [`distinct`] is never NULL.
173///
174/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
175/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
176/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
177/// to treat them as equal, please normalize zeros before calling this kernel. See
178/// [`f32::total_cmp`] and [`f64::total_cmp`].
179///
180/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
181/// For comparisons involving nested types see [`crate::ord::make_comparator`]
182pub fn distinct(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
183    compare_op(Op::Distinct, lhs, rhs)
184}
185
186/// Perform `left IS NOT DISTINCT FROM right` operation on two [`Datum`]
187///
188/// [`not_distinct`] is similar to [`eq`], only differing in null handling. In particular, two
189/// operands are considered `NOT DISTINCT` if they have the same value or if both of them
190/// is NULL. The result of [`not_distinct`] is never NULL.
191///
192/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
193/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
194/// Note that totalOrder treats positive and negative zeros as different. If it is necessary
195/// to treat them as equal, please normalize zeros before calling this kernel. See
196/// [`f32::total_cmp`] and [`f64::total_cmp`].
197///
198/// Nested types, such as lists, are not supported as the null semantics are not well-defined.
199/// For comparisons involving nested types see [`crate::ord::make_comparator`]
200pub fn not_distinct(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
201    compare_op(Op::NotDistinct, lhs, rhs)
202}
203
204/// Perform `op` on the provided `Datum`
205#[inline(never)]
206fn compare_op(op: Op, lhs: &dyn Datum, rhs: &dyn Datum) -> Result<BooleanArray, ArrowError> {
207    use arrow_schema::DataType::*;
208    let (l, l_s) = lhs.get();
209    let (r, r_s) = rhs.get();
210
211    let l_len = l.len();
212    let r_len = r.len();
213
214    if l_len != r_len && !l_s && !r_s {
215        return Err(ArrowError::InvalidArgumentError(format!(
216            "Cannot compare arrays of different lengths, got {l_len} vs {r_len}"
217        )));
218    }
219
220    let len = match l_s {
221        true => r_len,
222        false => l_len,
223    };
224
225    let l_nulls = l.logical_nulls();
226    let r_nulls = r.logical_nulls();
227
228    let l_v = l.as_any_dictionary_opt();
229    let l = l_v.map(|x| x.values().as_ref()).unwrap_or(l);
230    let l_t = l.data_type();
231
232    let r_v = r.as_any_dictionary_opt();
233    let r = r_v.map(|x| x.values().as_ref()).unwrap_or(r);
234    let r_t = r.data_type();
235
236    if r_t.is_nested() || l_t.is_nested() {
237        return Err(ArrowError::InvalidArgumentError(format!(
238            "Nested comparison: {l_t} {op} {r_t} (hint: use make_comparator instead)"
239        )));
240    } else if l_t != r_t {
241        return Err(ArrowError::InvalidArgumentError(format!(
242            "Invalid comparison operation: {l_t} {op} {r_t}"
243        )));
244    }
245
246    // Defer computation as may not be necessary
247    let values = || -> BooleanBuffer {
248        let d = downcast_primitive_array! {
249            (l, r) => apply(op, l.values().as_ref(), l_s, l_v, r.values().as_ref(), r_s, r_v),
250            (Boolean, Boolean) => apply(op, l.as_boolean(), l_s, l_v, r.as_boolean(), r_s, r_v),
251            (Utf8, Utf8) => apply(op, l.as_string::<i32>(), l_s, l_v, r.as_string::<i32>(), r_s, r_v),
252            (Utf8View, Utf8View) => apply(op, l.as_string_view(), l_s, l_v, r.as_string_view(), r_s, r_v),
253            (LargeUtf8, LargeUtf8) => apply(op, l.as_string::<i64>(), l_s, l_v, r.as_string::<i64>(), r_s, r_v),
254            (Binary, Binary) => apply(op, l.as_binary::<i32>(), l_s, l_v, r.as_binary::<i32>(), r_s, r_v),
255            (BinaryView, BinaryView) => apply(op, l.as_binary_view(), l_s, l_v, r.as_binary_view(), r_s, r_v),
256            (LargeBinary, LargeBinary) => apply(op, l.as_binary::<i64>(), l_s, l_v, r.as_binary::<i64>(), r_s, r_v),
257            (FixedSizeBinary(_), FixedSizeBinary(_)) => apply(op, l.as_fixed_size_binary(), l_s, l_v, r.as_fixed_size_binary(), r_s, r_v),
258            (Null, Null) => None,
259            _ => unreachable!(),
260        };
261        d.unwrap_or_else(|| BooleanBuffer::new_unset(len))
262    };
263
264    let l_nulls = l_nulls.filter(|n| n.null_count() > 0);
265    let r_nulls = r_nulls.filter(|n| n.null_count() > 0);
266    Ok(match (l_nulls, l_s, r_nulls, r_s) {
267        (Some(l), true, Some(r), true) | (Some(l), false, Some(r), false) => {
268            // Either both sides are scalar or neither side is scalar
269            match op {
270                Op::Distinct => {
271                    let values = values();
272                    let l = l.inner().bit_chunks().iter_padded();
273                    let r = r.inner().bit_chunks().iter_padded();
274                    let ne = values.bit_chunks().iter_padded();
275
276                    let c = |((l, r), n)| (l ^ r) | (l & r & n);
277                    let buffer = l.zip(r).zip(ne).map(c).collect();
278                    BooleanBuffer::new(buffer, 0, len).into()
279                }
280                Op::NotDistinct => {
281                    let values = values();
282                    let l = l.inner().bit_chunks().iter_padded();
283                    let r = r.inner().bit_chunks().iter_padded();
284                    let e = values.bit_chunks().iter_padded();
285
286                    let c = |((l, r), e)| u64::not(l | r) | (l & r & e);
287                    let buffer = l.zip(r).zip(e).map(c).collect();
288                    BooleanBuffer::new(buffer, 0, len).into()
289                }
290                _ => BooleanArray::new(values(), NullBuffer::union(Some(&l), Some(&r))),
291            }
292        }
293        (Some(_), true, Some(a), false) | (Some(a), false, Some(_), true) => {
294            // Scalar is null, other side is non-scalar and nullable
295            match op {
296                Op::Distinct => a.into_inner().into(),
297                Op::NotDistinct => a.into_inner().not().into(),
298                _ => BooleanArray::new_null(len),
299            }
300        }
301        (Some(nulls), is_scalar, None, _) | (None, _, Some(nulls), is_scalar) => {
302            // Only one side is nullable
303            match is_scalar {
304                true => match op {
305                    // Scalar is null, other side is not nullable
306                    Op::Distinct => BooleanBuffer::new_set(len).into(),
307                    Op::NotDistinct => BooleanBuffer::new_unset(len).into(),
308                    _ => BooleanArray::new_null(len),
309                },
310                false => match op {
311                    Op::Distinct => {
312                        let values = values();
313                        let l = nulls.inner().bit_chunks().iter_padded();
314                        let ne = values.bit_chunks().iter_padded();
315                        let c = |(l, n)| u64::not(l) | n;
316                        let buffer = l.zip(ne).map(c).collect();
317                        BooleanBuffer::new(buffer, 0, len).into()
318                    }
319                    Op::NotDistinct => (nulls.inner() & &values()).into(),
320                    _ => BooleanArray::new(values(), Some(nulls)),
321                },
322            }
323        }
324        // Neither side is nullable
325        (None, _, None, _) => BooleanArray::new(values(), None),
326    })
327}
328
329/// Perform a potentially vectored `op` on the provided `ArrayOrd`
330fn apply<T: ArrayOrd>(
331    op: Op,
332    l: T,
333    l_s: bool,
334    l_v: Option<&dyn AnyDictionaryArray>,
335    r: T,
336    r_s: bool,
337    r_v: Option<&dyn AnyDictionaryArray>,
338) -> Option<BooleanBuffer> {
339    if l.len() == 0 || r.len() == 0 {
340        return None; // Handle empty dictionaries
341    }
342
343    if !l_s && !r_s && (l_v.is_some() || r_v.is_some()) {
344        // Not scalar and at least one side has a dictionary, need to perform vectored comparison
345        let l_v = l_v
346            .map(|x| x.normalized_keys())
347            .unwrap_or_else(|| (0..l.len()).collect());
348
349        let r_v = r_v
350            .map(|x| x.normalized_keys())
351            .unwrap_or_else(|| (0..r.len()).collect());
352
353        assert_eq!(l_v.len(), r_v.len()); // Sanity check
354
355        Some(match op {
356            Op::Equal | Op::NotDistinct => apply_op_vectored(l, &l_v, r, &r_v, false, T::is_eq),
357            Op::NotEqual | Op::Distinct => apply_op_vectored(l, &l_v, r, &r_v, true, T::is_eq),
358            Op::Less => apply_op_vectored(l, &l_v, r, &r_v, false, T::is_lt),
359            Op::LessEqual => apply_op_vectored(r, &r_v, l, &l_v, true, T::is_lt),
360            Op::Greater => apply_op_vectored(r, &r_v, l, &l_v, false, T::is_lt),
361            Op::GreaterEqual => apply_op_vectored(l, &l_v, r, &r_v, true, T::is_lt),
362        })
363    } else {
364        let l_s = l_s.then(|| l_v.map(|x| x.normalized_keys()[0]).unwrap_or_default());
365        let r_s = r_s.then(|| r_v.map(|x| x.normalized_keys()[0]).unwrap_or_default());
366
367        let buffer = match op {
368            Op::Equal | Op::NotDistinct => apply_op(l, l_s, r, r_s, false, T::is_eq),
369            Op::NotEqual | Op::Distinct => apply_op(l, l_s, r, r_s, true, T::is_eq),
370            Op::Less => apply_op(l, l_s, r, r_s, false, T::is_lt),
371            Op::LessEqual => apply_op(r, r_s, l, l_s, true, T::is_lt),
372            Op::Greater => apply_op(r, r_s, l, l_s, false, T::is_lt),
373            Op::GreaterEqual => apply_op(l, l_s, r, r_s, true, T::is_lt),
374        };
375
376        // If a side had a dictionary, and was not scalar, we need to materialize this
377        Some(match (l_v, r_v) {
378            (Some(l_v), _) if l_s.is_none() => take_bits(l_v, buffer),
379            (_, Some(r_v)) if r_s.is_none() => take_bits(r_v, buffer),
380            _ => buffer,
381        })
382    }
383}
384
385/// Perform a take operation on `buffer` with the given dictionary
386fn take_bits(v: &dyn AnyDictionaryArray, buffer: BooleanBuffer) -> BooleanBuffer {
387    let array = take(&BooleanArray::new(buffer, None), v.keys(), None).unwrap();
388    array.as_boolean().values().clone()
389}
390
391/// Invokes `f` with values `0..len` collecting the boolean results into a new `BooleanBuffer`
392///
393/// This is similar to [`arrow_buffer::MutableBuffer::collect_bool`] but with
394/// the option to efficiently negate the result
395fn collect_bool(len: usize, neg: bool, f: impl Fn(usize) -> bool) -> BooleanBuffer {
396    let mut buffer = Vec::with_capacity(ceil(len, 64));
397
398    let chunks = len / 64;
399    let remainder = len % 64;
400    buffer.extend((0..chunks).map(|chunk| {
401        let mut packed = 0;
402        for bit_idx in 0..64 {
403            let i = bit_idx + chunk * 64;
404            packed |= (f(i) as u64) << bit_idx;
405        }
406        if neg {
407            packed = !packed
408        }
409
410        packed
411    }));
412
413    if remainder != 0 {
414        let mut packed = 0;
415        for bit_idx in 0..remainder {
416            let i = bit_idx + chunks * 64;
417            packed |= (f(i) as u64) << bit_idx;
418        }
419        if neg {
420            packed = !packed
421        }
422
423        buffer.push(packed);
424    }
425    BooleanBuffer::new(buffer.into(), 0, len)
426}
427
428/// Applies `op` to possibly scalar `ArrayOrd`
429///
430/// If l is scalar `l_s` will be `Some(idx)` where `idx` is the index of the scalar value in `l`
431/// If r is scalar `r_s` will be `Some(idx)` where `idx` is the index of the scalar value in `r`
432///
433/// If `neg` is true the result of `op` will be negated
434fn apply_op<T: ArrayOrd>(
435    l: T,
436    l_s: Option<usize>,
437    r: T,
438    r_s: Option<usize>,
439    neg: bool,
440    op: impl Fn(T::Item, T::Item) -> bool,
441) -> BooleanBuffer {
442    match (l_s, r_s) {
443        (None, None) => {
444            assert_eq!(l.len(), r.len());
445            collect_bool(l.len(), neg, |idx| unsafe {
446                op(l.value_unchecked(idx), r.value_unchecked(idx))
447            })
448        }
449        (Some(l_s), Some(r_s)) => {
450            let a = l.value(l_s);
451            let b = r.value(r_s);
452            std::iter::once(op(a, b) ^ neg).collect()
453        }
454        (Some(l_s), None) => {
455            let v = l.value(l_s);
456            collect_bool(r.len(), neg, |idx| op(v, unsafe { r.value_unchecked(idx) }))
457        }
458        (None, Some(r_s)) => {
459            let v = r.value(r_s);
460            collect_bool(l.len(), neg, |idx| op(unsafe { l.value_unchecked(idx) }, v))
461        }
462    }
463}
464
465/// Applies `op` to possibly scalar `ArrayOrd` with the given indices
466fn apply_op_vectored<T: ArrayOrd>(
467    l: T,
468    l_v: &[usize],
469    r: T,
470    r_v: &[usize],
471    neg: bool,
472    op: impl Fn(T::Item, T::Item) -> bool,
473) -> BooleanBuffer {
474    assert_eq!(l_v.len(), r_v.len());
475    collect_bool(l_v.len(), neg, |idx| unsafe {
476        let l_idx = *l_v.get_unchecked(idx);
477        let r_idx = *r_v.get_unchecked(idx);
478        op(l.value_unchecked(l_idx), r.value_unchecked(r_idx))
479    })
480}
481
482trait ArrayOrd {
483    type Item: Copy;
484
485    fn len(&self) -> usize;
486
487    fn value(&self, idx: usize) -> Self::Item {
488        assert!(idx < self.len());
489        unsafe { self.value_unchecked(idx) }
490    }
491
492    /// # Safety
493    ///
494    /// Safe if `idx < self.len()`
495    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item;
496
497    fn is_eq(l: Self::Item, r: Self::Item) -> bool;
498
499    fn is_lt(l: Self::Item, r: Self::Item) -> bool;
500}
501
502impl ArrayOrd for &BooleanArray {
503    type Item = bool;
504
505    fn len(&self) -> usize {
506        Array::len(self)
507    }
508
509    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item {
510        unsafe { BooleanArray::value_unchecked(self, idx) }
511    }
512
513    fn is_eq(l: Self::Item, r: Self::Item) -> bool {
514        l == r
515    }
516
517    fn is_lt(l: Self::Item, r: Self::Item) -> bool {
518        !l & r
519    }
520}
521
522impl<T: ArrowNativeTypeOp> ArrayOrd for &[T] {
523    type Item = T;
524
525    fn len(&self) -> usize {
526        (*self).len()
527    }
528
529    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item {
530        unsafe { *self.get_unchecked(idx) }
531    }
532
533    fn is_eq(l: Self::Item, r: Self::Item) -> bool {
534        l.is_eq(r)
535    }
536
537    fn is_lt(l: Self::Item, r: Self::Item) -> bool {
538        l.is_lt(r)
539    }
540}
541
542impl<'a, T: ByteArrayType> ArrayOrd for &'a GenericByteArray<T> {
543    type Item = &'a [u8];
544
545    fn len(&self) -> usize {
546        Array::len(self)
547    }
548
549    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item {
550        unsafe { GenericByteArray::value_unchecked(self, idx).as_ref() }
551    }
552
553    fn is_eq(l: Self::Item, r: Self::Item) -> bool {
554        l == r
555    }
556
557    fn is_lt(l: Self::Item, r: Self::Item) -> bool {
558        l < r
559    }
560}
561
562impl<'a, T: ByteViewType> ArrayOrd for &'a GenericByteViewArray<T> {
563    /// This is the item type for the GenericByteViewArray::compare
564    /// Item.0 is the array, Item.1 is the index
565    type Item = (&'a GenericByteViewArray<T>, usize);
566
567    #[inline(always)]
568    fn is_eq(l: Self::Item, r: Self::Item) -> bool {
569        let l_view = unsafe { l.0.views().get_unchecked(l.1) };
570        let r_view = unsafe { r.0.views().get_unchecked(r.1) };
571        if l.0.data_buffers().is_empty() && r.0.data_buffers().is_empty() {
572            // For eq case, we can directly compare the inlined bytes
573            return l_view == r_view;
574        }
575
576        let l_len = *l_view as u32;
577        let r_len = *r_view as u32;
578        // This is a fast path for equality check.
579        // We don't need to look at the actual bytes to determine if they are equal.
580        if l_len != r_len {
581            return false;
582        }
583        if l_len == 0 && r_len == 0 {
584            return true;
585        }
586
587        // # Safety
588        // The index is within bounds as it is checked in value()
589        unsafe { GenericByteViewArray::compare_unchecked(l.0, l.1, r.0, r.1).is_eq() }
590    }
591
592    #[inline(always)]
593    fn is_lt(l: Self::Item, r: Self::Item) -> bool {
594        // If both arrays use only the inline buffer
595        if l.0.data_buffers().is_empty() && r.0.data_buffers().is_empty() {
596            let l_view = unsafe { l.0.views().get_unchecked(l.1) };
597            let r_view = unsafe { r.0.views().get_unchecked(r.1) };
598            return GenericByteViewArray::<T>::inline_key_fast(*l_view)
599                < GenericByteViewArray::<T>::inline_key_fast(*r_view);
600        }
601
602        // Fallback to the generic, unchecked comparison for non-inline cases
603        // # Safety
604        // The index is within bounds as it is checked in value()
605        unsafe { GenericByteViewArray::compare_unchecked(l.0, l.1, r.0, r.1).is_lt() }
606    }
607
608    fn len(&self) -> usize {
609        Array::len(self)
610    }
611
612    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item {
613        (self, idx)
614    }
615}
616
617impl<'a> ArrayOrd for &'a FixedSizeBinaryArray {
618    type Item = &'a [u8];
619
620    fn len(&self) -> usize {
621        Array::len(self)
622    }
623
624    unsafe fn value_unchecked(&self, idx: usize) -> Self::Item {
625        unsafe { FixedSizeBinaryArray::value_unchecked(self, idx) }
626    }
627
628    fn is_eq(l: Self::Item, r: Self::Item) -> bool {
629        l == r
630    }
631
632    fn is_lt(l: Self::Item, r: Self::Item) -> bool {
633        l < r
634    }
635}
636
637/// Compares two [`GenericByteViewArray`] at index `left_idx` and `right_idx`
638#[inline(always)]
639pub fn compare_byte_view<T: ByteViewType>(
640    left: &GenericByteViewArray<T>,
641    left_idx: usize,
642    right: &GenericByteViewArray<T>,
643    right_idx: usize,
644) -> Ordering {
645    assert!(left_idx < left.len());
646    assert!(right_idx < right.len());
647    if left.data_buffers().is_empty() && right.data_buffers().is_empty() {
648        let l_view = unsafe { left.views().get_unchecked(left_idx) };
649        let r_view = unsafe { right.views().get_unchecked(right_idx) };
650        return GenericByteViewArray::<T>::inline_key_fast(*l_view)
651            .cmp(&GenericByteViewArray::<T>::inline_key_fast(*r_view));
652    }
653    unsafe { GenericByteViewArray::compare_unchecked(left, left_idx, right, right_idx) }
654}
655
656#[cfg(test)]
657mod tests {
658    use std::sync::Arc;
659
660    use arrow_array::{DictionaryArray, Int32Array, Scalar, StringArray};
661
662    use super::*;
663
664    #[test]
665    fn test_null_dict() {
666        let a = DictionaryArray::new(Int32Array::new_null(10), Arc::new(Int32Array::new_null(0)));
667        let r = eq(&a, &a).unwrap();
668        assert_eq!(r.null_count(), 10);
669
670        let a = DictionaryArray::new(
671            Int32Array::from(vec![1, 2, 3, 4, 5, 6]),
672            Arc::new(Int32Array::new_null(10)),
673        );
674        let r = eq(&a, &a).unwrap();
675        assert_eq!(r.null_count(), 6);
676
677        let scalar =
678            DictionaryArray::new(Int32Array::new_null(1), Arc::new(Int32Array::new_null(0)));
679        let r = eq(&a, &Scalar::new(&scalar)).unwrap();
680        assert_eq!(r.null_count(), 6);
681
682        let scalar =
683            DictionaryArray::new(Int32Array::new_null(1), Arc::new(Int32Array::new_null(0)));
684        let r = eq(&Scalar::new(&scalar), &Scalar::new(&scalar)).unwrap();
685        assert_eq!(r.null_count(), 1);
686
687        let a = DictionaryArray::new(
688            Int32Array::from(vec![0, 1, 2]),
689            Arc::new(Int32Array::from(vec![3, 2, 1])),
690        );
691        let r = eq(&a, &Scalar::new(&scalar)).unwrap();
692        assert_eq!(r.null_count(), 3);
693    }
694
695    #[test]
696    fn is_distinct_from_non_nulls() {
697        let left_int_array = Int32Array::from(vec![0, 1, 2, 3, 4]);
698        let right_int_array = Int32Array::from(vec![4, 3, 2, 1, 0]);
699
700        assert_eq!(
701            BooleanArray::from(vec![true, true, false, true, true,]),
702            distinct(&left_int_array, &right_int_array).unwrap()
703        );
704        assert_eq!(
705            BooleanArray::from(vec![false, false, true, false, false,]),
706            not_distinct(&left_int_array, &right_int_array).unwrap()
707        );
708    }
709
710    #[test]
711    fn is_distinct_from_nulls() {
712        // [0, 0, NULL, 0, 0, 0]
713        let left_int_array = Int32Array::new(
714            vec![0, 0, 1, 3, 0, 0].into(),
715            Some(NullBuffer::from(vec![true, true, false, true, true, true])),
716        );
717        // [0, NULL, NULL, NULL, 0, NULL]
718        let right_int_array = Int32Array::new(
719            vec![0; 6].into(),
720            Some(NullBuffer::from(vec![
721                true, false, false, false, true, false,
722            ])),
723        );
724
725        assert_eq!(
726            BooleanArray::from(vec![false, true, false, true, false, true,]),
727            distinct(&left_int_array, &right_int_array).unwrap()
728        );
729
730        assert_eq!(
731            BooleanArray::from(vec![true, false, true, false, true, false,]),
732            not_distinct(&left_int_array, &right_int_array).unwrap()
733        );
734    }
735
736    #[test]
737    fn test_distinct_scalar() {
738        let a = Int32Array::new_scalar(12);
739        let b = Int32Array::new_scalar(12);
740        assert!(!distinct(&a, &b).unwrap().value(0));
741        assert!(not_distinct(&a, &b).unwrap().value(0));
742
743        let a = Int32Array::new_scalar(12);
744        let b = Int32Array::new_null(1);
745        assert!(distinct(&a, &b).unwrap().value(0));
746        assert!(!not_distinct(&a, &b).unwrap().value(0));
747        assert!(distinct(&b, &a).unwrap().value(0));
748        assert!(!not_distinct(&b, &a).unwrap().value(0));
749
750        let b = Scalar::new(b);
751        assert!(distinct(&a, &b).unwrap().value(0));
752        assert!(!not_distinct(&a, &b).unwrap().value(0));
753
754        assert!(!distinct(&b, &b).unwrap().value(0));
755        assert!(not_distinct(&b, &b).unwrap().value(0));
756
757        let a = Int32Array::new(
758            vec![0, 1, 2, 3].into(),
759            Some(vec![false, false, true, true].into()),
760        );
761        let expected = BooleanArray::from(vec![false, false, true, true]);
762        assert_eq!(distinct(&a, &b).unwrap(), expected);
763        assert_eq!(distinct(&b, &a).unwrap(), expected);
764
765        let expected = BooleanArray::from(vec![true, true, false, false]);
766        assert_eq!(not_distinct(&a, &b).unwrap(), expected);
767        assert_eq!(not_distinct(&b, &a).unwrap(), expected);
768
769        let b = Int32Array::new_scalar(1);
770        let expected = BooleanArray::from(vec![true; 4]);
771        assert_eq!(distinct(&a, &b).unwrap(), expected);
772        assert_eq!(distinct(&b, &a).unwrap(), expected);
773        let expected = BooleanArray::from(vec![false; 4]);
774        assert_eq!(not_distinct(&a, &b).unwrap(), expected);
775        assert_eq!(not_distinct(&b, &a).unwrap(), expected);
776
777        let b = Int32Array::new_scalar(3);
778        let expected = BooleanArray::from(vec![true, true, true, false]);
779        assert_eq!(distinct(&a, &b).unwrap(), expected);
780        assert_eq!(distinct(&b, &a).unwrap(), expected);
781        let expected = BooleanArray::from(vec![false, false, false, true]);
782        assert_eq!(not_distinct(&a, &b).unwrap(), expected);
783        assert_eq!(not_distinct(&b, &a).unwrap(), expected);
784    }
785
786    #[test]
787    fn test_scalar_negation() {
788        let a = Int32Array::new_scalar(54);
789        let b = Int32Array::new_scalar(54);
790        let r = eq(&a, &b).unwrap();
791        assert!(r.value(0));
792
793        let r = neq(&a, &b).unwrap();
794        assert!(!r.value(0))
795    }
796
797    #[test]
798    fn test_scalar_empty() {
799        let a = Int32Array::new_null(0);
800        let b = Int32Array::new_scalar(23);
801        let r = eq(&a, &b).unwrap();
802        assert_eq!(r.len(), 0);
803        let r = eq(&b, &a).unwrap();
804        assert_eq!(r.len(), 0);
805    }
806
807    #[test]
808    fn test_dictionary_nulls() {
809        let values = StringArray::from(vec![Some("us-west"), Some("us-east")]);
810        let nulls = NullBuffer::from(vec![false, true, true]);
811
812        let key_values = vec![100i32, 1i32, 0i32].into();
813        let keys = Int32Array::new(key_values, Some(nulls));
814        let col = DictionaryArray::try_new(keys, Arc::new(values)).unwrap();
815
816        neq(&col.slice(0, col.len() - 1), &col.slice(1, col.len() - 1)).unwrap();
817    }
818}