Path: blob/main/crates/polars-arrow/src/compute/arity.rs
6939 views
//! Defines kernels suitable to perform operations to primitive arrays.12use super::utils::{check_same_len, combine_validities_and};3use crate::array::PrimitiveArray;4use crate::datatypes::ArrowDataType;5use crate::types::NativeType;67/// Applies an unary and infallible function to a [`PrimitiveArray`].8///9/// This is the /// fastest way to perform an operation on a [`PrimitiveArray`] when the benefits10/// of a vectorized operation outweighs the cost of branching nulls and non-nulls.11///12/// # Implementation13/// This will apply the function for all values, including those on null slots.14/// This implies that the operation must be infallible for any value of the15/// corresponding type or this function may panic.16#[inline]17pub fn unary<I, F, O>(array: &PrimitiveArray<I>, op: F, dtype: ArrowDataType) -> PrimitiveArray<O>18where19I: NativeType,20O: NativeType,21F: Fn(I) -> O,22{23let values = array.values().iter().map(|v| op(*v)).collect::<Vec<_>>();2425PrimitiveArray::<O>::new(dtype, values.into(), array.validity().cloned())26}2728/// Applies a binary operations to two primitive arrays.29///30/// This is the fastest way to perform an operation on two primitive array when the benefits of a31/// vectorized operation outweighs the cost of branching nulls and non-nulls.32///33/// # Errors34/// This function errors iff the arrays have a different length.35///36/// # Implementation37/// This will apply the function for all values, including those on null slots.38/// This implies that the operation must be infallible for any value of the39/// corresponding type.40/// The types of the arrays are not checked with this operation. The closure41/// "op" needs to handle the different types in the arrays. The datatype for the42/// resulting array has to be selected by the implementer of the function as43/// an argument for the function.44#[inline]45pub fn binary<T, D, F>(46lhs: &PrimitiveArray<T>,47rhs: &PrimitiveArray<D>,48dtype: ArrowDataType,49op: F,50) -> PrimitiveArray<T>51where52T: NativeType,53D: NativeType,54F: Fn(T, D) -> T,55{56check_same_len(lhs, rhs).unwrap();5758let validity = combine_validities_and(lhs.validity(), rhs.validity());5960let values = lhs61.values()62.iter()63.zip(rhs.values().iter())64.map(|(l, r)| op(*l, *r))65.collect::<Vec<_>>()66.into();6768PrimitiveArray::<T>::new(dtype, values, validity)69}707172