Skip to main content

arrow_arith/
arity.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//! Kernels for operating on [`PrimitiveArray`]s
6
7use arrow_array::builder::BufferBuilder;
8use arrow_array::*;
9use arrow_buffer::ArrowNativeType;
10use arrow_buffer::MutableBuffer;
11use arrow_buffer::buffer::NullBuffer;
12use arrow_data::ArrayData;
13use arrow_schema::ArrowError;
14
15/// See [`PrimitiveArray::unary`]
16pub fn unary<I, F, O>(array: &PrimitiveArray<I>, op: F) -> PrimitiveArray<O>
17where
18    I: ArrowPrimitiveType,
19    O: ArrowPrimitiveType,
20    F: Fn(I::Native) -> O::Native,
21{
22    array.unary(op)
23}
24
25/// See [`PrimitiveArray::unary_mut`]
26pub fn unary_mut<I, F>(
27    array: PrimitiveArray<I>,
28    op: F,
29) -> Result<PrimitiveArray<I>, PrimitiveArray<I>>
30where
31    I: ArrowPrimitiveType,
32    F: Fn(I::Native) -> I::Native,
33{
34    array.unary_mut(op)
35}
36
37/// See [`PrimitiveArray::try_unary`]
38pub fn try_unary<I, F, O>(array: &PrimitiveArray<I>, op: F) -> Result<PrimitiveArray<O>, ArrowError>
39where
40    I: ArrowPrimitiveType,
41    O: ArrowPrimitiveType,
42    F: Fn(I::Native) -> Result<O::Native, ArrowError>,
43{
44    array.try_unary(op)
45}
46
47/// See [`PrimitiveArray::try_unary_mut`]
48pub fn try_unary_mut<I, F>(
49    array: PrimitiveArray<I>,
50    op: F,
51) -> Result<Result<PrimitiveArray<I>, ArrowError>, PrimitiveArray<I>>
52where
53    I: ArrowPrimitiveType,
54    F: Fn(I::Native) -> Result<I::Native, ArrowError>,
55{
56    array.try_unary_mut(op)
57}
58
59/// Applies a binary infallible function to two [`PrimitiveArray`]s,
60/// producing a new [`PrimitiveArray`]
61///
62/// # Details
63///
64/// Given two arrays of length `len`, calls `op(a[i], b[i])` for `i` in `0..len`, collecting
65/// the results in a [`PrimitiveArray`].
66///
67/// If any index is null in either `a` or `b`, the
68/// corresponding index in the result will also be null
69///
70/// Like [`unary`], the `op` is evaluated for every element in the two arrays,
71/// including those elements which are NULL. This is beneficial as the cost of
72/// the operation is low compared to the cost of branching, and especially when
73/// the operation can be vectorised, however, requires `op` to be infallible for
74/// all possible values of its inputs
75///
76/// # Errors
77///
78/// * if the arrays have different lengths.
79///
80/// # Example
81/// ```
82/// # use arrow_arith::arity::binary;
83/// # use arrow_array::{Float32Array, Int32Array};
84/// # use arrow_array::types::Int32Type;
85/// let a = Float32Array::from(vec![Some(5.1f32), None, Some(6.8), Some(7.2)]);
86/// let b = Int32Array::from(vec![1, 2, 4, 9]);
87/// // compute int(a) + b for each element
88/// let c = binary(&a, &b, |a, b| a as i32 + b).unwrap();
89/// assert_eq!(c, Int32Array::from(vec![Some(6), None, Some(10), Some(16)]));
90/// ```
91pub fn binary<A, B, F, O>(
92    a: &PrimitiveArray<A>,
93    b: &PrimitiveArray<B>,
94    op: F,
95) -> Result<PrimitiveArray<O>, ArrowError>
96where
97    A: ArrowPrimitiveType,
98    B: ArrowPrimitiveType,
99    O: ArrowPrimitiveType,
100    F: Fn(A::Native, B::Native) -> O::Native,
101{
102    if a.len() != b.len() {
103        return Err(ArrowError::ComputeError(
104            "Cannot perform binary operation on arrays of different length".to_string(),
105        ));
106    }
107
108    if a.is_empty() {
109        return Ok(PrimitiveArray::from(ArrayData::new_empty(&O::DATA_TYPE)));
110    }
111
112    let nulls = NullBuffer::union(a.logical_nulls().as_ref(), b.logical_nulls().as_ref());
113
114    let values = a
115        .values()
116        .into_iter()
117        .zip(b.values())
118        .map(|(l, r)| op(*l, *r));
119
120    let buffer: Vec<_> = values.collect();
121    Ok(PrimitiveArray::new(buffer.into(), nulls))
122}
123
124/// Applies a binary and infallible function to values in two arrays, replacing
125/// the values in the first array in place.
126///
127/// # Details
128///
129/// Given two arrays of length `len`, calls `op(a[i], b[i])` for `i` in
130/// `0..len`, modifying the [`PrimitiveArray`] `a` in place, if possible.
131///
132/// If any index is null in either `a` or `b`, the corresponding index in the
133/// result will also be null.
134///
135/// # Buffer Reuse
136///
137/// If the underlying buffers in `a` are not shared with other arrays,  mutates
138/// the underlying buffer in place, without allocating.
139///
140/// If the underlying buffer in `a` are shared, returns Err(self)
141///
142/// Like [`unary`] the provided function is evaluated for every index, ignoring validity. This
143/// is beneficial when the cost of the operation is low compared to the cost of branching, and
144/// especially when the operation can be vectorised, however, requires `op` to be infallible
145/// for all possible values of its inputs
146///
147/// # Errors
148///
149/// * If the arrays have different lengths
150/// * If the array is not mutable (see "Buffer Reuse")
151///
152/// # See Also
153///
154/// * Documentation on [`PrimitiveArray::unary_mut`] for operating on [`ArrayRef`].
155///
156/// # Example
157/// ```
158/// # use arrow_arith::arity::binary_mut;
159/// # use arrow_array::{Float32Array, Int32Array};
160/// # use arrow_array::types::Int32Type;
161/// // compute a + b for each element
162/// let a = Float32Array::from(vec![Some(5.1f32), None, Some(6.8)]);
163/// let b = Int32Array::from(vec![Some(1), None, Some(2)]);
164/// // compute a + b, updating the value in a in place if possible
165/// let a = binary_mut(a, &b, |a, b| a + b as f32).unwrap().unwrap();
166/// // a is updated in place
167/// assert_eq!(a, Float32Array::from(vec![Some(6.1), None, Some(8.8)]));
168/// ```
169///
170/// # Example with shared buffers
171/// ```
172/// # use arrow_arith::arity::binary_mut;
173/// # use arrow_array::Float32Array;
174/// # use arrow_array::types::Int32Type;
175/// let a = Float32Array::from(vec![Some(5.1f32), None, Some(6.8)]);
176/// let b = Float32Array::from(vec![Some(1.0f32), None, Some(2.0)]);
177/// // a_clone shares the buffer with a
178/// let a_cloned = a.clone();
179/// // try to update a in place, but it is shared. Returns Err(a)
180/// let a = binary_mut(a, &b, |a, b| a + b).unwrap_err();
181/// assert_eq!(a_cloned, a);
182/// // drop shared reference
183/// drop(a_cloned);
184/// // now a is not shared, so we can update it in place
185/// let a = binary_mut(a, &b, |a, b| a + b).unwrap().unwrap();
186/// assert_eq!(a, Float32Array::from(vec![Some(6.1), None, Some(8.8)]));
187/// ```
188pub fn binary_mut<T, U, F>(
189    a: PrimitiveArray<T>,
190    b: &PrimitiveArray<U>,
191    op: F,
192) -> Result<Result<PrimitiveArray<T>, ArrowError>, PrimitiveArray<T>>
193where
194    T: ArrowPrimitiveType,
195    U: ArrowPrimitiveType,
196    F: Fn(T::Native, U::Native) -> T::Native,
197{
198    if a.len() != b.len() {
199        return Ok(Err(ArrowError::ComputeError(
200            "Cannot perform binary operation on arrays of different length".to_string(),
201        )));
202    }
203
204    if a.is_empty() {
205        return Ok(Ok(PrimitiveArray::from(ArrayData::new_empty(
206            &T::DATA_TYPE,
207        ))));
208    }
209
210    let mut builder = a.into_builder()?;
211
212    builder
213        .values_slice_mut()
214        .iter_mut()
215        .zip(b.values())
216        .for_each(|(l, r)| *l = op(*l, *r));
217
218    let array = builder.finish();
219
220    // The builder has the null buffer from `a`, it is not changed.
221    let nulls = NullBuffer::union(array.logical_nulls().as_ref(), b.logical_nulls().as_ref());
222
223    let array_builder = array.into_data().into_builder().nulls(nulls);
224
225    let array_data = unsafe { array_builder.build_unchecked() };
226    Ok(Ok(PrimitiveArray::<T>::from(array_data)))
227}
228
229/// Applies the provided fallible binary operation across `a` and `b`.
230///
231/// This will return any error encountered, or collect the results into
232/// a [`PrimitiveArray`]. If any index is null in either `a`
233/// or `b`, the corresponding index in the result will also be null
234///
235/// Like [`try_unary`] the function is only evaluated for non-null indices
236///
237/// # Errors
238///
239/// Returns an error if the arrays have different lengths,
240/// or if the operation returns one.
241pub fn try_binary<A: ArrayAccessor, B: ArrayAccessor, F, O>(
242    a: A,
243    b: B,
244    op: F,
245) -> Result<PrimitiveArray<O>, ArrowError>
246where
247    O: ArrowPrimitiveType,
248    F: Fn(A::Item, B::Item) -> Result<O::Native, ArrowError>,
249{
250    if a.len() != b.len() {
251        return Err(ArrowError::ComputeError(
252            "Cannot perform a binary operation on arrays of different length".to_string(),
253        ));
254    }
255    if a.is_empty() {
256        return Ok(PrimitiveArray::from(ArrayData::new_empty(&O::DATA_TYPE)));
257    }
258    let len = a.len();
259
260    // Physical nulls are not the whole story: a `RunArray` or `DictionaryArray` can have
261    // logical nulls in its values while its own null buffer is absent. `is_nullable` covers
262    // those, but is allowed to be conservative, so the union of the logical nulls can still
263    // be empty.
264    if !a.is_nullable() && !b.is_nullable() {
265        try_binary_no_nulls(len, a, b, op)
266    } else {
267        let Some(nulls) = NullBuffer::union(a.logical_nulls().as_ref(), b.logical_nulls().as_ref())
268        else {
269            return try_binary_no_nulls(len, a, b, op);
270        };
271
272        let mut buffer = BufferBuilder::<O::Native>::new(len);
273        buffer.append_n_zeroed(len);
274        let slice = buffer.as_slice_mut();
275
276        nulls.try_for_each_valid_idx(|idx| {
277            unsafe {
278                *slice.get_unchecked_mut(idx) = op(a.value_unchecked(idx), b.value_unchecked(idx))?
279            };
280            Ok::<_, ArrowError>(())
281        })?;
282
283        let values = buffer.finish().into();
284        Ok(PrimitiveArray::new(values, Some(nulls)))
285    }
286}
287
288/// Applies the provided fallible binary operation across `a` and `b` by mutating the mutable
289/// [`PrimitiveArray`] `a` with the results.
290///
291/// Returns any error encountered, or collects the results into a [`PrimitiveArray`] as return
292/// value. If any index is null in either `a` or `b`, the corresponding index in the result will
293/// also be null.
294///
295/// Like [`try_unary`] the function is only evaluated for non-null indices.
296///
297/// See [`binary_mut`] for errors and buffer reuse information.
298pub fn try_binary_mut<T, F>(
299    a: PrimitiveArray<T>,
300    b: &PrimitiveArray<T>,
301    op: F,
302) -> Result<Result<PrimitiveArray<T>, ArrowError>, PrimitiveArray<T>>
303where
304    T: ArrowPrimitiveType,
305    F: Fn(T::Native, T::Native) -> Result<T::Native, ArrowError>,
306{
307    if a.len() != b.len() {
308        return Ok(Err(ArrowError::ComputeError(
309            "Cannot perform binary operation on arrays of different length".to_string(),
310        )));
311    }
312    let len = a.len();
313
314    if a.is_empty() {
315        return Ok(Ok(PrimitiveArray::from(ArrayData::new_empty(
316            &T::DATA_TYPE,
317        ))));
318    }
319
320    // Physical and logical nulls coincide for a `PrimitiveArray`, but gate on `is_nullable` to
321    // match `try_binary`. That check is allowed to be conservative, so fall back to the no-nulls
322    // path when the union of the logical nulls turns out to be empty, instead of unwrapping it.
323    if !a.is_nullable() && !b.is_nullable() {
324        try_binary_no_nulls_mut(len, a, b, op)
325    } else {
326        let Some(nulls) =
327            create_union_null_buffer(a.logical_nulls().as_ref(), b.logical_nulls().as_ref())
328        else {
329            return try_binary_no_nulls_mut(len, a, b, op);
330        };
331
332        let mut builder = a.into_builder()?;
333
334        let slice = builder.values_slice_mut();
335
336        let r = nulls.try_for_each_valid_idx(|idx| {
337            unsafe {
338                *slice.get_unchecked_mut(idx) =
339                    op(*slice.get_unchecked(idx), b.value_unchecked(idx))?
340            };
341            Ok::<_, ArrowError>(())
342        });
343        if let Err(err) = r {
344            return Ok(Err(err));
345        }
346        let array_builder = builder.finish().into_data().into_builder();
347        let array_data = unsafe { array_builder.nulls(Some(nulls)).build_unchecked() };
348        Ok(Ok(PrimitiveArray::<T>::from(array_data)))
349    }
350}
351
352/// Computes the union of the nulls in two optional [`NullBuffer`] which
353/// is not shared with the input buffers.
354///
355/// The union of the nulls is the same as `NullBuffer::union(lhs, rhs)` but
356/// it does not increase the reference count of the null buffer.
357fn create_union_null_buffer(
358    lhs: Option<&NullBuffer>,
359    rhs: Option<&NullBuffer>,
360) -> Option<NullBuffer> {
361    match (lhs, rhs) {
362        (Some(lhs), Some(rhs)) => Some(NullBuffer::new(lhs.inner() & rhs.inner())),
363        (Some(n), None) | (None, Some(n)) => Some(NullBuffer::new(n.inner() & n.inner())),
364        (None, None) => None,
365    }
366}
367
368/// This intentional inline(never) attribute helps LLVM optimize the loop.
369#[inline(never)]
370fn try_binary_no_nulls<A: ArrayAccessor, B: ArrayAccessor, F, O>(
371    len: usize,
372    a: A,
373    b: B,
374    op: F,
375) -> Result<PrimitiveArray<O>, ArrowError>
376where
377    O: ArrowPrimitiveType,
378    F: Fn(A::Item, B::Item) -> Result<O::Native, ArrowError>,
379{
380    let capacity = len
381        .checked_mul(O::Native::get_byte_width())
382        .ok_or_else(|| ArrowError::MemoryError("binary output size overflow".to_string()))?;
383    let mut buffer = MutableBuffer::try_with_capacity(capacity)
384        .map_err(|e| ArrowError::MemoryError(e.to_string()))?;
385    for idx in 0..len {
386        unsafe {
387            buffer.push_unchecked(op(a.value_unchecked(idx), b.value_unchecked(idx))?);
388        };
389    }
390    Ok(PrimitiveArray::new(buffer.into(), None))
391}
392
393/// This intentional inline(never) attribute helps LLVM optimize the loop.
394#[inline(never)]
395fn try_binary_no_nulls_mut<T, F>(
396    len: usize,
397    a: PrimitiveArray<T>,
398    b: &PrimitiveArray<T>,
399    op: F,
400) -> Result<Result<PrimitiveArray<T>, ArrowError>, PrimitiveArray<T>>
401where
402    T: ArrowPrimitiveType,
403    F: Fn(T::Native, T::Native) -> Result<T::Native, ArrowError>,
404{
405    let mut builder = a.into_builder()?;
406    let slice = builder.values_slice_mut();
407
408    for idx in 0..len {
409        unsafe {
410            match op(*slice.get_unchecked(idx), b.value_unchecked(idx)) {
411                Ok(value) => *slice.get_unchecked_mut(idx) = value,
412                Err(err) => return Ok(Err(err)),
413            }
414        };
415    }
416    Ok(Ok(builder.finish()))
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422    use arrow_array::types::*;
423    use std::sync::Arc;
424
425    #[test]
426    fn test_unary_f64_slice() {
427        let input = Float64Array::from(vec![Some(5.1f64), None, Some(6.8), None, Some(7.2)]);
428        let input_slice = input.slice(1, 4);
429        let result = unary(&input_slice, |n| n.round());
430        assert_eq!(
431            result,
432            Float64Array::from(vec![None, Some(7.0), None, Some(7.0)])
433        );
434    }
435
436    #[test]
437    fn test_try_binary_run_array_logical_nulls() {
438        // A `RunArray` has no null buffer of its own, so its logical nulls live in the values.
439        let run_ends = Int32Array::from(vec![1, 2, 3]);
440        let values = Int32Array::from(vec![Some(10), None, Some(30)]);
441        let run = RunArray::<Int32Type>::try_new(&run_ends, &values).expect("valid run array");
442        assert_eq!(run.null_count(), 0);
443        assert_eq!(run.logical_null_count(), 1);
444
445        let typed = run.downcast::<Int32Array>().expect("Int32 values");
446        let other = Int32Array::from(vec![1, 1, 1]);
447        let result =
448            try_binary::<_, _, _, Int32Type>(typed, &other, |a, b| Ok(a + b)).expect("no overflow");
449        assert_eq!(result, Int32Array::from(vec![Some(11), None, Some(31)]));
450    }
451
452    #[test]
453    fn test_binary_mut() {
454        let a = Int32Array::from(vec![15, 14, 9, 8, 1]);
455        let b = Int32Array::from(vec![Some(1), None, Some(3), None, Some(5)]);
456        let c = binary_mut(a, &b, |l, r| l + r).unwrap().unwrap();
457
458        let expected = Int32Array::from(vec![Some(16), None, Some(12), None, Some(6)]);
459        assert_eq!(c, expected);
460    }
461
462    #[test]
463    fn test_binary_mut_null_buffer() {
464        let a = Int32Array::from(vec![Some(3), Some(4), Some(5), Some(6), None]);
465
466        let b = Int32Array::from(vec![Some(10), Some(11), Some(12), Some(13), Some(14)]);
467
468        let r1 = binary_mut(a, &b, |a, b| a + b).unwrap();
469
470        let a = Int32Array::from(vec![Some(3), Some(4), Some(5), Some(6), None]);
471        let b = Int32Array::new(
472            vec![10, 11, 12, 13, 14].into(),
473            Some(vec![true, true, true, true, true].into()),
474        );
475
476        // unwrap here means that no copying occurred
477        let r2 = binary_mut(a, &b, |a, b| a + b).unwrap();
478        assert_eq!(r1.unwrap(), r2.unwrap());
479    }
480
481    #[test]
482    fn test_try_binary_mut() {
483        let a = Int32Array::from(vec![15, 14, 9, 8, 1]);
484        let b = Int32Array::from(vec![Some(1), None, Some(3), None, Some(5)]);
485        let c = try_binary_mut(a, &b, |l, r| Ok(l + r)).unwrap().unwrap();
486
487        let expected = Int32Array::from(vec![Some(16), None, Some(12), None, Some(6)]);
488        assert_eq!(c, expected);
489
490        let a = Int32Array::from(vec![15, 14, 9, 8, 1]);
491        let b = Int32Array::from(vec![1, 2, 3, 4, 5]);
492        let c = try_binary_mut(a, &b, |l, r| Ok(l + r)).unwrap().unwrap();
493        let expected = Int32Array::from(vec![16, 16, 12, 12, 6]);
494        assert_eq!(c, expected);
495
496        let a = Int32Array::from(vec![15, 14, 9, 8, 1]);
497        let b = Int32Array::from(vec![Some(1), None, Some(3), None, Some(5)]);
498        let _ = try_binary_mut(a, &b, |l, r| {
499            if l == 1 {
500                Err(ArrowError::InvalidArgumentError(
501                    "got error".parse().unwrap(),
502                ))
503            } else {
504                Ok(l + r)
505            }
506        })
507        .unwrap()
508        .expect_err("should got error");
509    }
510
511    #[test]
512    fn test_try_binary_mut_null_buffer() {
513        let a = Int32Array::from(vec![Some(3), Some(4), Some(5), Some(6), None]);
514
515        let b = Int32Array::from(vec![Some(10), Some(11), Some(12), Some(13), Some(14)]);
516
517        let r1 = try_binary_mut(a, &b, |a, b| Ok(a + b)).unwrap();
518
519        let a = Int32Array::from(vec![Some(3), Some(4), Some(5), Some(6), None]);
520        let b = Int32Array::new(
521            vec![10, 11, 12, 13, 14].into(),
522            Some(vec![true, true, true, true, true].into()),
523        );
524
525        // unwrap here means that no copying occurred
526        let r2 = try_binary_mut(a, &b, |a, b| Ok(a + b)).unwrap();
527        assert_eq!(r1.unwrap(), r2.unwrap());
528    }
529
530    #[test]
531    fn test_try_binary_mut_all_valid_null_buffers() {
532        // Both arrays carry a null buffer with no nulls in it: the no-nulls path must still run.
533        let a = Int32Array::new(vec![1, 2].into(), Some(vec![true, true].into()));
534        let b = Int32Array::new(vec![10, 20].into(), Some(vec![true, true].into()));
535        let c = try_binary_mut(a, &b, |a, b| Ok(a + b))
536            .expect("not shared")
537            .expect("no overflow");
538        assert_eq!(c, Int32Array::from(vec![11, 22]));
539        assert_eq!(c.logical_null_count(), 0);
540    }
541
542    #[test]
543    fn test_unary_dict_mut() {
544        let values = Int32Array::from(vec![Some(10), Some(20), None]);
545        let keys = Int8Array::from_iter_values([0, 0, 1, 2]);
546        let dictionary = DictionaryArray::new(keys, Arc::new(values));
547
548        let updated = dictionary.unary_mut::<_, Int32Type>(|x| x + 1).unwrap();
549        let typed = updated.downcast_dict::<Int32Array>().unwrap();
550        assert_eq!(typed.value(0), 11);
551        assert_eq!(typed.value(1), 11);
552        assert_eq!(typed.value(2), 21);
553
554        let values = updated.values();
555        assert!(values.is_null(2));
556    }
557}