Path: blob/main/crates/polars-compute/src/gather/boolean.rs
6939 views
use arrow::array::{Array, BooleanArray, PrimitiveArray};1use arrow::bitmap::{Bitmap, BitmapBuilder};2use polars_utils::IdxSize;34use super::bitmap::{take_bitmap_nulls_unchecked, take_bitmap_unchecked};56// Take implementation when neither values nor indices contain nulls.7unsafe fn take_no_validity(values: &Bitmap, indices: &[IdxSize]) -> (Bitmap, Option<Bitmap>) {8(take_bitmap_unchecked(values, indices), None)9}1011// Take implementation when only values contain nulls.12unsafe fn take_values_validity(13values: &BooleanArray,14indices: &[IdxSize],15) -> (Bitmap, Option<Bitmap>) {16let validity_values = values.validity().unwrap();17let validity = take_bitmap_unchecked(validity_values, indices);1819let values_values = values.values();20let buffer = take_bitmap_unchecked(values_values, indices);2122(buffer, validity.into())23}2425// Take implementation when only indices contain nulls.26unsafe fn take_indices_validity(27values: &Bitmap,28indices: &PrimitiveArray<IdxSize>,29) -> (Bitmap, Option<Bitmap>) {30let buffer = take_bitmap_nulls_unchecked(values, indices);31(buffer, indices.validity().cloned())32}3334// Take implementation when both values and indices contain nulls.35unsafe fn take_values_indices_validity(36values: &BooleanArray,37indices: &PrimitiveArray<IdxSize>,38) -> (Bitmap, Option<Bitmap>) {39let mut validity = BitmapBuilder::with_capacity(indices.len());4041let values_validity = values.validity().unwrap();4243let values_values = values.values();44let values = indices.iter().map(|index| match index {45Some(&index) => {46let index = index as usize;47debug_assert!(index < values.len());48validity.push(values_validity.get_bit_unchecked(index));49values_values.get_bit_unchecked(index)50},51None => {52validity.push(false);53false54},55});56let values = Bitmap::from_trusted_len_iter(values);57(values, validity.into_opt_validity())58}5960/// `take` implementation for boolean arrays61/// # Safety62/// The indices must be in-bounds.63pub unsafe fn take_unchecked(64values: &BooleanArray,65indices: &PrimitiveArray<IdxSize>,66) -> BooleanArray {67let dtype = values.dtype().clone();68let indices_has_validity = indices.null_count() > 0;69let values_has_validity = values.null_count() > 0;7071let (values, validity) = match (values_has_validity, indices_has_validity) {72(false, false) => take_no_validity(values.values(), indices.values()),73(true, false) => take_values_validity(values, indices.values()),74(false, true) => take_indices_validity(values.values(), indices),75(true, true) => take_values_indices_validity(values, indices),76};7778BooleanArray::new(dtype, values, validity)79}808182