• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vortex-data / vortex / 16992684502

15 Aug 2025 02:56PM UTC coverage: 87.875% (+0.2%) from 87.72%
16992684502

Pull #2456

github

web-flow
Merge 2d540e578 into 4a23f65b3
Pull Request #2456: feat: basic BoolBuffer / BoolBufferMut

1275 of 1428 new or added lines in 110 files covered. (89.29%)

334 existing lines in 31 files now uncovered.

57169 of 65057 relevant lines covered (87.88%)

658056.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

82.85
/vortex-array/src/compute/compare.rs
1
// SPDX-License-Identifier: Apache-2.0
2
// SPDX-FileCopyrightText: Copyright the Vortex contributors
3

4
use core::fmt;
5
use std::any::Any;
6
use std::fmt::{Display, Formatter};
7
use std::sync::LazyLock;
8

9
use arcref::ArcRef;
10
use arrow_ord::cmp;
11
use vortex_buffer::BitBuffer;
12
use vortex_dtype::{DType, NativePType, Nullability};
13
use vortex_error::{VortexError, VortexExpect, VortexResult, vortex_bail, vortex_err};
14
use vortex_scalar::Scalar;
15

16
use crate::arrays::ConstantArray;
17
use crate::arrow::{Datum, from_arrow_array_with_len};
18
use crate::compute::{ComputeFn, ComputeFnVTable, InvocationArgs, Kernel, Options, Output};
19
use crate::vtable::VTable;
20
use crate::{Array, ArrayRef, Canonical, IntoArray};
21

22
static COMPARE_FN: LazyLock<ComputeFn> = LazyLock::new(|| {
7,925✔
23
    let compute = ComputeFn::new("compare".into(), ArcRef::new_ref(&Compare));
7,925✔
24
    for kernel in inventory::iter::<CompareKernelRef> {
55,441✔
25
        compute.register_kernel(kernel.0.clone());
47,516✔
26
    }
47,516✔
27
    compute
7,925✔
28
});
7,925✔
29

30
/// Compares two arrays and returns a new boolean array with the result of the comparison.
31
/// Or, returns None if comparison is not supported for these arrays.
32
pub fn compare(left: &dyn Array, right: &dyn Array, operator: Operator) -> VortexResult<ArrayRef> {
95,754✔
33
    COMPARE_FN
95,754✔
34
        .invoke(&InvocationArgs {
95,754✔
35
            inputs: &[left.into(), right.into()],
95,754✔
36
            options: &operator,
95,754✔
37
        })?
95,754✔
38
        .unwrap_array()
95,754✔
39
}
95,754✔
40

41
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Hash)]
42
pub enum Operator {
43
    /// Equality (`=`)
44
    Eq,
45
    /// Inequality (`!=`)
46
    NotEq,
47
    /// Greater than (`>`)
48
    Gt,
49
    /// Greater than or equal (`>=`)
50
    Gte,
51
    /// Less than (`<`)
52
    Lt,
53
    /// Less than or equal (`<=`)
54
    Lte,
55
}
56

57
impl Display for Operator {
58
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
×
59
        let display = match &self {
×
60
            Operator::Eq => "=",
×
61
            Operator::NotEq => "!=",
×
62
            Operator::Gt => ">",
×
63
            Operator::Gte => ">=",
×
64
            Operator::Lt => "<",
×
65
            Operator::Lte => "<=",
×
66
        };
67
        Display::fmt(display, f)
×
68
    }
×
69
}
70

71
impl Operator {
72
    pub fn inverse(self) -> Self {
×
73
        match self {
×
74
            Operator::Eq => Operator::NotEq,
×
75
            Operator::NotEq => Operator::Eq,
×
76
            Operator::Gt => Operator::Lte,
×
77
            Operator::Gte => Operator::Lt,
×
78
            Operator::Lt => Operator::Gte,
×
79
            Operator::Lte => Operator::Gt,
×
80
        }
81
    }
×
82

83
    /// Change the sides of the operator, where changing lhs and rhs won't change the result of the operation
84
    pub fn swap(self) -> Self {
68,156✔
85
        match self {
68,156✔
86
            Operator::Eq => Operator::Eq,
23,350✔
87
            Operator::NotEq => Operator::NotEq,
5,521✔
88
            Operator::Gt => Operator::Lt,
14,850✔
89
            Operator::Gte => Operator::Lte,
6,631✔
90
            Operator::Lt => Operator::Gt,
10,093✔
91
            Operator::Lte => Operator::Gte,
7,711✔
92
        }
93
    }
68,156✔
94
}
95

96
pub struct CompareKernelRef(ArcRef<dyn Kernel>);
97
inventory::collect!(CompareKernelRef);
98

99
pub trait CompareKernel: VTable {
100
    fn compare(
101
        &self,
102
        lhs: &Self::Array,
103
        rhs: &dyn Array,
104
        operator: Operator,
105
    ) -> VortexResult<Option<ArrayRef>>;
106
}
107

108
#[derive(Debug)]
109
pub struct CompareKernelAdapter<V: VTable>(pub V);
110

111
impl<V: VTable + CompareKernel> CompareKernelAdapter<V> {
112
    pub const fn lift(&'static self) -> CompareKernelRef {
×
113
        CompareKernelRef(ArcRef::new_ref(self))
×
114
    }
×
115
}
116

117
impl<V: VTable + CompareKernel> Kernel for CompareKernelAdapter<V> {
118
    fn invoke(&self, args: &InvocationArgs) -> VortexResult<Option<Output>> {
667,318✔
119
        let inputs = CompareArgs::try_from(args)?;
667,318✔
120
        let Some(array) = inputs.lhs.as_opt::<V>() else {
667,318✔
121
            return Ok(None);
596,940✔
122
        };
123
        Ok(V::compare(&self.0, array, inputs.rhs, inputs.operator)?.map(|array| array.into()))
70,378✔
124
    }
667,318✔
125
}
126

127
struct Compare;
128

129
impl ComputeFnVTable for Compare {
130
    fn invoke(
95,754✔
131
        &self,
95,754✔
132
        args: &InvocationArgs,
95,754✔
133
        kernels: &[ArcRef<dyn Kernel>],
95,754✔
134
    ) -> VortexResult<Output> {
95,754✔
135
        let CompareArgs { lhs, rhs, operator } = CompareArgs::try_from(args)?;
95,754✔
136

137
        let return_dtype = self.return_dtype(args)?;
95,754✔
138

139
        if lhs.is_empty() {
95,754✔
140
            return Ok(Canonical::empty(&return_dtype).into_array().into());
1✔
141
        }
95,753✔
142

143
        let left_constant_null = lhs.as_constant().map(|l| l.is_null()).unwrap_or(false);
95,753✔
144
        let right_constant_null = rhs.as_constant().map(|r| r.is_null()).unwrap_or(false);
95,753✔
145
        if left_constant_null || right_constant_null {
95,753✔
146
            return Ok(ConstantArray::new(Scalar::null(return_dtype), lhs.len())
2,118✔
147
                .into_array()
2,118✔
148
                .into());
2,118✔
149
        }
93,635✔
150

151
        let right_is_constant = rhs.is_constant();
93,635✔
152

153
        // Always try to put constants on the right-hand side so encodings can optimise themselves.
154
        if lhs.is_constant() && !right_is_constant {
93,635✔
155
            return Ok(compare(rhs, lhs, operator.swap())?.into());
11,008✔
156
        }
82,627✔
157

158
        // First try lhs op rhs, then invert and try again.
159
        for kernel in kernels {
521,601✔
160
            if let Some(output) = kernel.invoke(args)? {
464,453✔
161
                return Ok(output);
25,479✔
162
            }
438,974✔
163
        }
164
        if let Some(output) = lhs.invoke(&COMPARE_FN, args)? {
57,148✔
165
            return Ok(output);
×
166
        }
57,148✔
167

168
        // Try inverting the operator and swapping the arguments
169
        let inverted_args = InvocationArgs {
57,148✔
170
            inputs: &[rhs.into(), lhs.into()],
57,148✔
171
            options: &operator.swap(),
57,148✔
172
        };
57,148✔
173
        for kernel in kernels {
353,521✔
174
            if let Some(output) = kernel.invoke(&inverted_args)? {
305,652✔
175
                return Ok(output);
9,279✔
176
            }
296,373✔
177
        }
178
        if let Some(output) = rhs.invoke(&COMPARE_FN, &inverted_args)? {
47,869✔
179
            return Ok(output);
×
180
        }
47,869✔
181

182
        // Only log missing compare implementation if there's possibly better one than arrow,
183
        // i.e. lhs isn't arrow or rhs isn't arrow or constant
184
        if !(lhs.is_arrow() && (rhs.is_arrow() || right_is_constant)) {
47,869✔
185
            log::debug!(
33,305✔
186
                "No compare implementation found for LHS {}, RHS {}, and operator {} (or inverse)",
×
187
                lhs.encoding_id(),
×
188
                rhs.encoding_id(),
×
189
                operator,
190
            );
191
        }
14,564✔
192

193
        // Fallback to arrow on canonical types
194
        Ok(arrow_compare(lhs, rhs, operator)?.into())
47,869✔
195
    }
95,754✔
196

197
    fn return_dtype(&self, args: &InvocationArgs) -> VortexResult<DType> {
191,508✔
198
        let CompareArgs { lhs, rhs, .. } = CompareArgs::try_from(args)?;
191,508✔
199

200
        if !lhs.dtype().eq_ignore_nullability(rhs.dtype()) {
191,508✔
UNCOV
201
            vortex_bail!(
×
UNCOV
202
                "Cannot compare different DTypes {} and {}",
×
UNCOV
203
                lhs.dtype(),
×
UNCOV
204
                rhs.dtype()
×
205
            );
206
        }
191,508✔
207

208
        // TODO(ngates): no reason why not
209
        if lhs.dtype().is_struct() {
191,508✔
210
            vortex_bail!(
×
211
                "Compare does not support arrays with Struct DType, got: {} and {}",
×
212
                lhs.dtype(),
×
213
                rhs.dtype()
×
214
            )
215
        }
191,508✔
216

217
        Ok(DType::Bool(
191,508✔
218
            lhs.dtype().nullability() | rhs.dtype().nullability(),
191,508✔
219
        ))
191,508✔
220
    }
191,508✔
221

222
    fn return_len(&self, args: &InvocationArgs) -> VortexResult<usize> {
95,754✔
223
        let CompareArgs { lhs, rhs, .. } = CompareArgs::try_from(args)?;
95,754✔
224
        if lhs.len() != rhs.len() {
95,754✔
225
            vortex_bail!(
×
226
                "Compare operations only support arrays of the same length, got {} and {}",
×
227
                lhs.len(),
×
228
                rhs.len()
×
229
            );
230
        }
95,754✔
231
        Ok(lhs.len())
95,754✔
232
    }
95,754✔
233

234
    fn is_elementwise(&self) -> bool {
95,754✔
235
        true
95,754✔
236
    }
95,754✔
237
}
238

239
struct CompareArgs<'a> {
240
    lhs: &'a dyn Array,
241
    rhs: &'a dyn Array,
242
    operator: Operator,
243
}
244

245
impl Options for Operator {
246
    fn as_any(&self) -> &dyn Any {
1,153,121✔
247
        self
1,153,121✔
248
    }
1,153,121✔
249
}
250

251
impl<'a> TryFrom<&InvocationArgs<'a>> for CompareArgs<'a> {
252
    type Error = VortexError;
253

254
    fn try_from(value: &InvocationArgs<'a>) -> Result<Self, Self::Error> {
1,153,121✔
255
        if value.inputs.len() != 2 {
1,153,121✔
256
            vortex_bail!("Expected 2 inputs, found {}", value.inputs.len());
×
257
        }
1,153,121✔
258
        let lhs = value.inputs[0]
1,153,121✔
259
            .array()
1,153,121✔
260
            .ok_or_else(|| vortex_err!("Expected first input to be an array"))?;
1,153,121✔
261
        let rhs = value.inputs[1]
1,153,121✔
262
            .array()
1,153,121✔
263
            .ok_or_else(|| vortex_err!("Expected second input to be an array"))?;
1,153,121✔
264
        let operator = *value
1,153,121✔
265
            .options
1,153,121✔
266
            .as_any()
1,153,121✔
267
            .downcast_ref::<Operator>()
1,153,121✔
268
            .vortex_expect("Expected options to be an operator");
1,153,121✔
269

270
        Ok(CompareArgs { lhs, rhs, operator })
1,153,121✔
271
    }
1,153,121✔
272
}
273

274
/// Helper function to compare empty values with arrays that have external value length information
275
/// like `VarBin`.
276
pub fn compare_lengths_to_empty<P, I>(lengths: I, op: Operator) -> BitBuffer
62✔
277
where
62✔
278
    P: NativePType,
62✔
279
    I: Iterator<Item = P>,
62✔
280
{
281
    // All comparison can be expressed in terms of equality. "" is the absolute min of possible value.
282
    let cmp_fn = match op {
62✔
283
        Operator::Eq | Operator::Lte => |v| v == P::zero(),
166✔
284
        Operator::NotEq | Operator::Gt => |v| v != P::zero(),
48✔
285
        Operator::Gte => |_| true,
286
        Operator::Lt => |_| false,
287
    };
288

289
    lengths.map(cmp_fn).collect()
62✔
290
}
62✔
291

292
/// Implementation of `CompareFn` using the Arrow crate.
293
fn arrow_compare(
47,870✔
294
    left: &dyn Array,
47,870✔
295
    right: &dyn Array,
47,870✔
296
    operator: Operator,
47,870✔
297
) -> VortexResult<ArrayRef> {
47,870✔
298
    let nullable = left.dtype().is_nullable() || right.dtype().is_nullable();
47,870✔
299
    let lhs = Datum::try_new(left)?;
47,870✔
300
    let rhs = Datum::try_new(right)?;
47,870✔
301

302
    let array = match operator {
47,870✔
303
        Operator::Eq => cmp::eq(&lhs, &rhs)?,
15,290✔
304
        Operator::NotEq => cmp::neq(&lhs, &rhs)?,
4,032✔
305
        Operator::Gt => cmp::gt(&lhs, &rhs)?,
12,716✔
306
        Operator::Gte => cmp::gt_eq(&lhs, &rhs)?,
5,571✔
307
        Operator::Lt => cmp::lt(&lhs, &rhs)?,
4,996✔
308
        Operator::Lte => cmp::lt_eq(&lhs, &rhs)?,
5,265✔
309
    };
310
    from_arrow_array_with_len(&array, left.len(), nullable)
47,870✔
311
}
47,870✔
312

313
pub fn scalar_cmp(lhs: &Scalar, rhs: &Scalar, operator: Operator) -> Scalar {
14,253✔
314
    if lhs.is_null() | rhs.is_null() {
14,253✔
315
        Scalar::null(DType::Bool(Nullability::Nullable))
×
316
    } else {
317
        let b = match operator {
14,253✔
318
            Operator::Eq => lhs == rhs,
3,336✔
319
            Operator::NotEq => lhs != rhs,
1,495✔
320
            Operator::Gt => lhs > rhs,
2,993✔
321
            Operator::Gte => lhs >= rhs,
1,138✔
322
            Operator::Lt => lhs < rhs,
4,165✔
323
            Operator::Lte => lhs <= rhs,
1,126✔
324
        };
325

326
        Scalar::bool(b, lhs.dtype().nullability() | rhs.dtype().nullability())
14,253✔
327
    }
328
}
14,253✔
329

330
#[cfg(test)]
331
mod tests {
332
    use rstest::rstest;
333

334
    use super::*;
335
    use crate::ToCanonical;
336
    use crate::arrays::{BoolArray, ConstantArray, VarBinArray, VarBinViewArray};
337
    use crate::test_harness::to_int_indices;
338
    use crate::validity::Validity;
339

340
    #[test]
341
    fn test_bool_basic_comparisons() {
1✔
342
        let arr = BoolArray::new(
1✔
343
            BitBuffer::from_iter([true, true, false, true, false]),
1✔
344
            Validity::from_iter([false, true, true, true, true]),
1✔
345
        );
346

347
        let matches = compare(arr.as_ref(), arr.as_ref(), Operator::Eq)
1✔
348
            .unwrap()
1✔
349
            .to_bool()
1✔
350
            .unwrap();
1✔
351

352
        assert_eq!(to_int_indices(matches).unwrap(), [1u64, 2, 3, 4]);
1✔
353

354
        let matches = compare(arr.as_ref(), arr.as_ref(), Operator::NotEq)
1✔
355
            .unwrap()
1✔
356
            .to_bool()
1✔
357
            .unwrap();
1✔
358
        let empty: [u64; 0] = [];
1✔
359
        assert_eq!(to_int_indices(matches).unwrap(), empty);
1✔
360

361
        let other = BoolArray::new(
1✔
362
            BitBuffer::from_iter([false, false, false, true, true]),
1✔
363
            Validity::from_iter([false, true, true, true, true]),
1✔
364
        );
365

366
        let matches = compare(arr.as_ref(), other.as_ref(), Operator::Lte)
1✔
367
            .unwrap()
1✔
368
            .to_bool()
1✔
369
            .unwrap();
1✔
370
        assert_eq!(to_int_indices(matches).unwrap(), [2u64, 3, 4]);
1✔
371

372
        let matches = compare(arr.as_ref(), other.as_ref(), Operator::Lt)
1✔
373
            .unwrap()
1✔
374
            .to_bool()
1✔
375
            .unwrap();
1✔
376
        assert_eq!(to_int_indices(matches).unwrap(), [4u64]);
1✔
377

378
        let matches = compare(other.as_ref(), arr.as_ref(), Operator::Gte)
1✔
379
            .unwrap()
1✔
380
            .to_bool()
1✔
381
            .unwrap();
1✔
382
        assert_eq!(to_int_indices(matches).unwrap(), [2u64, 3, 4]);
1✔
383

384
        let matches = compare(other.as_ref(), arr.as_ref(), Operator::Gt)
1✔
385
            .unwrap()
1✔
386
            .to_bool()
1✔
387
            .unwrap();
1✔
388
        assert_eq!(to_int_indices(matches).unwrap(), [4u64]);
1✔
389
    }
1✔
390

391
    #[test]
392
    fn constant_compare() {
1✔
393
        let left = ConstantArray::new(Scalar::from(2u32), 10);
1✔
394
        let right = ConstantArray::new(Scalar::from(10u32), 10);
1✔
395

396
        let compare = compare(left.as_ref(), right.as_ref(), Operator::Gt).unwrap();
1✔
397
        let res = compare.as_constant().unwrap();
1✔
398
        assert_eq!(res.as_bool().value(), Some(false));
1✔
399
        assert_eq!(compare.len(), 10);
1✔
400

401
        let compare = arrow_compare(&left.into_array(), &right.into_array(), Operator::Gt).unwrap();
1✔
402
        let res = compare.as_constant().unwrap();
1✔
403
        assert_eq!(res.as_bool().value(), Some(false));
1✔
404
        assert_eq!(compare.len(), 10);
1✔
405
    }
1✔
406

407
    #[rstest]
408
    #[case(Operator::Eq, vec![false, false, false, true])]
409
    #[case(Operator::NotEq, vec![true, true, true, false])]
410
    #[case(Operator::Gt, vec![true, true, true, false])]
411
    #[case(Operator::Gte, vec![true, true, true, true])]
412
    #[case(Operator::Lt, vec![false, false, false, false])]
413
    #[case(Operator::Lte, vec![false, false, false, true])]
414
    fn test_cmp_to_empty(#[case] op: Operator, #[case] expected: Vec<bool>) {
415
        let lengths: Vec<i32> = vec![1, 5, 7, 0];
416

417
        let output = compare_lengths_to_empty(lengths.iter().copied(), op);
418
        assert_eq!(Vec::from_iter(output.iter()), expected);
419
    }
420

421
    #[rstest]
422
    #[case(VarBinArray::from(vec!["a", "b"]).into_array(), VarBinViewArray::from_iter_str(["a", "b"]).into_array())]
423
    #[case(VarBinViewArray::from_iter_str(["a", "b"]).into_array(), VarBinArray::from(vec!["a", "b"]).into_array())]
424
    #[case(VarBinArray::from(vec!["a".as_bytes(), "b".as_bytes()]).into_array(), VarBinViewArray::from_iter_bin(["a".as_bytes(), "b".as_bytes()]).into_array())]
425
    #[case(VarBinViewArray::from_iter_bin(["a".as_bytes(), "b".as_bytes()]).into_array(), VarBinArray::from(vec!["a".as_bytes(), "b".as_bytes()]).into_array())]
426
    fn arrow_compare_different_encodings(#[case] left: ArrayRef, #[case] right: ArrayRef) {
427
        let res = compare(&left, &right, Operator::Eq).unwrap();
428
        assert_eq!(res.to_bool().unwrap().bit_buffer().true_count(), left.len());
429
    }
430
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc