Skip to main content

polars_core/series/arithmetic/
fixed_size_list.rs

1use polars_error::{PolarsResult, feature_gated};
2
3use super::list_utils::NumericOp;
4use super::{ArrayChunked, FixedSizeListType, IntoSeries, NumOpsDispatchInner, Series};
5
6impl NumOpsDispatchInner for FixedSizeListType {
7    fn add_to(lhs: &ArrayChunked, rhs: &Series) -> PolarsResult<Series> {
8        NumericFixedSizeListOp::add().execute(&lhs.clone().into_series(), rhs)
9    }
10
11    fn subtract(lhs: &ArrayChunked, rhs: &Series) -> PolarsResult<Series> {
12        NumericFixedSizeListOp::sub().execute(&lhs.clone().into_series(), rhs)
13    }
14
15    fn multiply(lhs: &ArrayChunked, rhs: &Series) -> PolarsResult<Series> {
16        NumericFixedSizeListOp::mul().execute(&lhs.clone().into_series(), rhs)
17    }
18
19    fn divide(lhs: &ArrayChunked, rhs: &Series) -> PolarsResult<Series> {
20        NumericFixedSizeListOp::div().execute(&lhs.clone().into_series(), rhs)
21    }
22
23    fn remainder(lhs: &ArrayChunked, rhs: &Series) -> PolarsResult<Series> {
24        NumericFixedSizeListOp::rem().execute(&lhs.clone().into_series(), rhs)
25    }
26}
27
28#[derive(Clone)]
29pub struct NumericFixedSizeListOp(NumericOp);
30
31impl NumericFixedSizeListOp {
32    pub fn add() -> Self {
33        Self(NumericOp::Add)
34    }
35
36    pub fn sub() -> Self {
37        Self(NumericOp::Sub)
38    }
39
40    pub fn mul() -> Self {
41        Self(NumericOp::Mul)
42    }
43
44    pub fn div() -> Self {
45        Self(NumericOp::Div)
46    }
47
48    pub fn rem() -> Self {
49        Self(NumericOp::Rem)
50    }
51
52    pub fn floor_div() -> Self {
53        Self(NumericOp::FloorDiv)
54    }
55
56    pub fn trunc_div() -> Self {
57        Self(NumericOp::TruncDiv)
58    }
59}
60
61impl NumericFixedSizeListOp {
62    #[cfg_attr(not(feature = "array_arithmetic"), allow(unused))]
63    pub fn execute(&self, lhs: &Series, rhs: &Series) -> PolarsResult<Series> {
64        feature_gated!("array_arithmetic", {
65            NumericFixedSizeListOpHelper::execute_op(self.clone(), lhs.rechunk(), rhs.rechunk())
66                .map(|x| x.into_series())
67        })
68    }
69}
70
71#[cfg(feature = "array_arithmetic")]
72use inner::NumericFixedSizeListOpHelper;
73
74#[cfg(feature = "array_arithmetic")]
75mod inner {
76    use fixed_size_list::NumericFixedSizeListOp;
77    use list_utils::with_match_pl_num_arith;
78    use num_traits::Zero;
79    use polars_arrow::bitmap::{Bitmap, BitmapBuilder};
80    use polars_arrow::compute::utils::combine_validities_and;
81    use polars_compute::arithmetic::pl_num::PlNumArithmetic;
82    use polars_utils::float::IsFloat;
83
84    use super::super::list_utils::{BinaryOpApplyType, Broadcast, NumericOp};
85    use super::super::*;
86
87    /// Utility to perform a binary operation between the primitive values of
88    /// 2 columns, where at least one of the columns is a `ArrayChunked` type.
89    pub(super) struct NumericFixedSizeListOpHelper {
90        op: NumericFixedSizeListOp,
91        output_name: PlSmallStr,
92        /// We are just re-using the enum used for list arithmetic.
93        op_apply_type: BinaryOpApplyType,
94        broadcast: Broadcast,
95        /// Stride of the leaf array
96        stride: usize,
97        /// Widths at every level
98        output_widths: Vec<usize>,
99        output_dtype: DataType,
100        output_primitive_dtype: DataType,
101        /// Length of the outermost level
102        output_len: usize,
103        data_lhs: (Series, Vec<Option<Bitmap>>),
104        data_rhs: (Series, Vec<Option<Bitmap>>),
105        swapped: bool,
106    }
107
108    /// This lets us separate some logic into `new()` to reduce the amount of
109    /// monomorphized code.
110    impl NumericFixedSizeListOpHelper {
111        /// Checks that:
112        /// * Dtypes are compatible:
113        ///   * list<->primitive | primitive<->list
114        ///   * list<->list both contain primitives (e.g. List<Int8>)
115        /// * Primitive dtypes match
116        /// * Lengths are compatible:
117        ///   * 1<->n | n<->1
118        ///   * n<->n
119        /// * Both sides have at least 1 non-NULL outer row.
120        ///
121        /// This returns an `Either` which may contain the final result to simplify
122        /// the implementation.
123        pub(super) fn execute_op(
124            op: NumericFixedSizeListOp,
125            lhs: Series,
126            rhs: Series,
127        ) -> PolarsResult<ArrayChunked> {
128            assert_eq!(lhs.chunks().len(), 1);
129            assert_eq!(rhs.chunks().len(), 1);
130
131            let dtype_lhs = lhs.dtype();
132            let dtype_rhs = rhs.dtype();
133
134            let prim_dtype_lhs = dtype_lhs.leaf_dtype();
135            let prim_dtype_rhs = dtype_rhs.leaf_dtype();
136
137            //
138            // Check leaf dtypes
139            //
140
141            if !(prim_dtype_lhs.is_supported_list_arithmetic_input()
142                && prim_dtype_rhs.is_supported_list_arithmetic_input())
143            {
144                polars_bail!(
145                    ComputeError: "cannot {} non-numeric inner dtypes: (left: {}, right: {})",
146                    op.0.name(), prim_dtype_lhs, prim_dtype_rhs
147                )
148            }
149
150            let output_primitive_dtype =
151                op.0.try_get_leaf_supertype(prim_dtype_lhs, prim_dtype_rhs)?;
152
153            fn is_array_type_at_all_levels(dtype: &DataType) -> bool {
154                match dtype {
155                    DataType::Array(inner, ..) => is_array_type_at_all_levels(inner),
156                    dt if dt.is_supported_list_arithmetic_input() => true,
157                    _ => false,
158                }
159            }
160
161            fn array_stride_and_widths(dtype: &DataType, widths: &mut Vec<usize>) -> usize {
162                if let DataType::Array(inner, size_inner) = dtype {
163                    widths.push(*size_inner);
164                    *size_inner * array_stride_and_widths(inner.as_ref(), widths)
165                } else {
166                    1
167                }
168            }
169
170            //
171            // Get broadcasting information and output length
172            //
173
174            let len_lhs = lhs.len();
175            let len_rhs = rhs.len();
176
177            let (broadcast, output_len) = match (len_lhs, len_rhs) {
178                (l, r) if l == r => (Broadcast::NoBroadcast, l),
179                (1, v) => (Broadcast::Left, v),
180                (v, 1) => (Broadcast::Right, v),
181                (l, r) => polars_bail!(
182                    ShapeMismatch:
183                    "cannot {} two columns of differing lengths: {} != {}",
184                    op.0.name(), l, r
185                ),
186            };
187
188            //
189            // Get validities for array levels
190            //
191
192            fn push_array_validities_recursive(s: &Series, out: &mut Vec<Option<Bitmap>>) {
193                let mut opt_arr = s.array().ok().map(|x| {
194                    assert_eq!(x.chunks().len(), 1);
195                    x.downcast_get(0).unwrap()
196                });
197
198                while let Some(arr) = opt_arr {
199                    // Push none if all-valid, this can potentially save some `repeat_bitmap()`
200                    // materializations on broadcasting paths.
201                    out.push(arr.validity().filter(|x| x.unset_bits() > 0).cloned());
202                    opt_arr = arr.values().as_any().downcast_ref::<FixedSizeListArray>();
203                }
204            }
205
206            let mut array_validities_lhs = vec![];
207            let mut array_validities_rhs = vec![];
208
209            push_array_validities_recursive(&lhs, &mut array_validities_lhs);
210            push_array_validities_recursive(&rhs, &mut array_validities_rhs);
211
212            let op_err_msg = |err_reason: &str| {
213                polars_err!(
214                    InvalidOperation:
215                    "cannot {} columns: {}: (left: {}, right: {})",
216                    op.0.name(), err_reason, dtype_lhs, dtype_rhs,
217                )
218            };
219
220            let ensure_array_type_at_all_levels = |dtype: &DataType| {
221                if !is_array_type_at_all_levels(dtype) {
222                    Err(op_err_msg("dtype was not array on all nesting levels"))
223                } else {
224                    Ok(())
225                }
226            };
227
228            //
229            // Check full dtypes and get output widths
230            //
231
232            let mut output_widths = vec![];
233
234            let (op_apply_type, stride, output_dtype) = match (dtype_lhs, dtype_rhs) {
235                (dtype_lhs @ DataType::Array(..), dtype_rhs @ DataType::Array(..)) => {
236                    // `get_arithmetic_field()` in the DSL checks this, but we also have to check here because if a user
237                    // directly adds 2 series together it bypasses the DSL.
238                    // This is currently duplicated code and should be replaced one day with an assert after Series ops get
239                    // checked properly.
240
241                    if dtype_lhs.cast_leaf(output_primitive_dtype.clone())
242                        != dtype_rhs.cast_leaf(output_primitive_dtype.clone())
243                    {
244                        return Err(op_err_msg("differing dtypes"));
245                    };
246
247                    // We only check dtype_lhs since we already checked dtype_lhs == dtype_rhs
248                    ensure_array_type_at_all_levels(dtype_lhs)?;
249
250                    let stride = array_stride_and_widths(dtype_lhs, &mut output_widths);
251
252                    // For array<->array without broadcasting we return early here to avoid the rest
253                    // of the setup code and dispatch layers.
254                    if let Broadcast::NoBroadcast = broadcast {
255                        let out = op.0.apply_series(
256                            &lhs.get_leaf_array().cast(&output_primitive_dtype)?,
257                            &rhs.get_leaf_array().cast(&output_primitive_dtype)?,
258                        );
259
260                        return Ok(finish_array_to_array_no_broadcast(
261                            lhs.name().clone(),
262                            &output_widths,
263                            output_len,
264                            &array_validities_lhs,
265                            &array_validities_rhs,
266                            out,
267                        ));
268                    }
269
270                    (BinaryOpApplyType::ListToList, stride, dtype_lhs)
271                },
272                (array_dtype @ DataType::Array(..), x)
273                    if x.is_supported_list_arithmetic_input() =>
274                {
275                    ensure_array_type_at_all_levels(array_dtype)?;
276
277                    let stride = array_stride_and_widths(array_dtype, &mut output_widths);
278                    (BinaryOpApplyType::ListToPrimitive, stride, array_dtype)
279                },
280                (x, array_dtype @ DataType::Array(..))
281                    if x.is_supported_list_arithmetic_input() =>
282                {
283                    ensure_array_type_at_all_levels(array_dtype)?;
284
285                    let stride = array_stride_and_widths(array_dtype, &mut output_widths);
286                    (BinaryOpApplyType::PrimitiveToList, stride, array_dtype)
287                },
288                (l, r) => polars_bail!(
289                    InvalidOperation:
290                    "cannot {} dtypes: {} != {}",
291                    op.0.name(), l, r,
292                ),
293            };
294
295            let output_dtype = output_dtype.cast_leaf(output_primitive_dtype.clone());
296
297            assert!(!output_widths.is_empty());
298
299            if cfg!(debug_assertions) {
300                match (array_validities_lhs.len(), array_validities_rhs.len()) {
301                    (l, r) if l == output_widths.len() && l == r && l > 0 => {},
302                    (v, 0) | (0, v) if v == output_widths.len() => {},
303                    _ => panic!(), // One side should have been an array.
304                }
305            }
306
307            if output_len == 0
308                || (matches!(
309                    &op_apply_type,
310                    BinaryOpApplyType::ListToList | BinaryOpApplyType::ListToPrimitive
311                ) && lhs.rechunk_validity().is_some_and(|x| x.set_bits() == 0))
312                || (matches!(
313                    &op_apply_type,
314                    BinaryOpApplyType::ListToList | BinaryOpApplyType::PrimitiveToList
315                ) && rhs.rechunk_validity().is_some_and(|x| x.set_bits() == 0))
316            {
317                let DataType::Array(inner_dtype, width) = output_dtype else {
318                    unreachable!()
319                };
320
321                Ok(ArrayChunked::full_null_with_dtype(
322                    lhs.name().clone(),
323                    output_len,
324                    inner_dtype.as_ref(),
325                    width,
326                ))
327            } else {
328                Self {
329                    op,
330                    output_name: lhs.name().clone(),
331                    op_apply_type,
332                    broadcast,
333                    stride,
334                    output_widths,
335                    output_dtype,
336                    output_primitive_dtype,
337                    output_len,
338                    data_lhs: (lhs, array_validities_lhs),
339                    data_rhs: (rhs, array_validities_rhs),
340                    swapped: false,
341                }
342                .finish()
343            }
344        }
345
346        pub(super) fn finish(mut self) -> PolarsResult<ArrayChunked> {
347            // We have physical codepaths for a subset of the possible combinations of broadcasting and
348            // column types. The remaining combinations are handled by dispatching to the physical
349            // codepaths after operand swapping.
350            //
351            // # Physical impl table
352            // Legend
353            // * |  N  | // impl "N"
354            // * | [N] | // dispatches to impl "N"
355            //
356            //                  |  L  |  N  |  R  | // Broadcast (L)eft, (N)oBroadcast, (R)ight
357            // ListToList       | [1] |  0  |  1  |
358            // ListToPrimitive  |  2  |  3  |  4  |
359            // PrimitiveToList  | [4] | [3] | [2] |
360
361            self.swapped = true;
362
363            match (&self.op_apply_type, &self.broadcast) {
364                // Mostly the same as ListNumericOp, however with fixed size list we also have
365                // (BinaryOpApplyType::ListToPrimitive, Broadcast::Left) as a physical impl.
366                (BinaryOpApplyType::ListToList, Broadcast::NoBroadcast) => unreachable!(), // We return earlier for this
367                (BinaryOpApplyType::ListToList, Broadcast::Right)
368                | (BinaryOpApplyType::ListToPrimitive, Broadcast::Left)
369                | (BinaryOpApplyType::ListToPrimitive, Broadcast::NoBroadcast)
370                | (BinaryOpApplyType::ListToPrimitive, Broadcast::Right) => {
371                    self.swapped = false;
372                    self._finish_impl_dispatch()
373                },
374                (BinaryOpApplyType::ListToList, Broadcast::Left) => {
375                    self.broadcast = Broadcast::Right;
376
377                    std::mem::swap(&mut self.data_lhs, &mut self.data_rhs);
378                    self._finish_impl_dispatch()
379                },
380                (BinaryOpApplyType::PrimitiveToList, Broadcast::Right) => {
381                    self.op_apply_type = BinaryOpApplyType::ListToPrimitive;
382                    self.broadcast = Broadcast::Left;
383
384                    std::mem::swap(&mut self.data_lhs, &mut self.data_rhs);
385                    self._finish_impl_dispatch()
386                },
387
388                (BinaryOpApplyType::PrimitiveToList, Broadcast::NoBroadcast) => {
389                    self.op_apply_type = BinaryOpApplyType::ListToPrimitive;
390
391                    std::mem::swap(&mut self.data_lhs, &mut self.data_rhs);
392                    self._finish_impl_dispatch()
393                },
394                (BinaryOpApplyType::PrimitiveToList, Broadcast::Left) => {
395                    self.op_apply_type = BinaryOpApplyType::ListToPrimitive;
396                    self.broadcast = Broadcast::Right;
397
398                    std::mem::swap(&mut self.data_lhs, &mut self.data_rhs);
399                    self._finish_impl_dispatch()
400                },
401            }
402        }
403
404        fn _finish_impl_dispatch(&mut self) -> PolarsResult<ArrayChunked> {
405            let output_dtype = self.output_dtype.clone();
406            let output_len = self.output_len;
407
408            let prim_lhs = self
409                .data_lhs
410                .0
411                .get_leaf_array()
412                .cast(&self.output_primitive_dtype)?
413                .rechunk();
414            let prim_rhs = self
415                .data_rhs
416                .0
417                .get_leaf_array()
418                .cast(&self.output_primitive_dtype)?
419                .rechunk();
420
421            debug_assert_eq!(prim_lhs.dtype(), prim_rhs.dtype());
422            let prim_dtype = prim_lhs.dtype();
423            debug_assert_eq!(prim_dtype, &self.output_primitive_dtype);
424
425            // Safety: Leaf dtypes have been checked to be numeric by `try_new()`
426            let out = with_match_physical_numeric_polars_type!(&prim_dtype, |$T| {
427                self._finish_impl::<$T>(prim_lhs, prim_rhs)
428            });
429
430            debug_assert_eq!(out.dtype(), &output_dtype);
431            assert_eq!(out.len(), output_len);
432
433            Ok(out)
434        }
435
436        /// Internal use only - contains physical impls.
437        fn _finish_impl<T: PolarsNumericType>(
438            &mut self,
439            prim_s_lhs: Series,
440            prim_s_rhs: Series,
441        ) -> ArrayChunked
442        where
443            T::Native: PlNumArithmetic,
444            PrimitiveArray<T::Native>:
445                polars_compute::comparisons::TotalEqKernel<Scalar = T::Native>,
446            T::Native: Zero + IsFloat,
447        {
448            let mut arr_lhs = {
449                let ca: &ChunkedArray<T> = prim_s_lhs.as_ref().as_ref();
450                assert_eq!(ca.chunks().len(), 1);
451                ca.downcast_get(0).unwrap().clone()
452            };
453
454            let mut arr_rhs = {
455                let ca: &ChunkedArray<T> = prim_s_rhs.as_ref().as_ref();
456                assert_eq!(ca.chunks().len(), 1);
457                ca.downcast_get(0).unwrap().clone()
458            };
459
460            self.op.0.prepare_numeric_op_side_validities::<T>(
461                &mut arr_lhs,
462                &mut arr_rhs,
463                self.swapped,
464            );
465
466            match (&self.op_apply_type, &self.broadcast) {
467                (BinaryOpApplyType::ListToList, Broadcast::Right) => {
468                    let mut out_vec: Vec<T::Native> =
469                        Vec::with_capacity(self.output_len * self.stride);
470                    let out_ptr: *mut T::Native = out_vec.as_mut_ptr();
471                    let stride = self.stride;
472
473                    with_match_pl_num_arith!(&self.op.0, self.swapped, |$OP| {
474                        unsafe {
475                            for outer_idx in 0..self.output_len {
476                                for inner_idx in 0..stride {
477                                    let l = arr_lhs.value_unchecked(stride * outer_idx + inner_idx);
478                                    let r = arr_rhs.value_unchecked(inner_idx);
479
480                                    *out_ptr.add(stride * outer_idx + inner_idx) = $OP(l, r);
481                                }
482                            }
483                        }
484                    });
485
486                    unsafe { out_vec.set_len(self.output_len * self.stride) };
487
488                    let leaf_validity = combine_validities_and(
489                        arr_lhs.validity(),
490                        arr_rhs
491                            .validity()
492                            .map(|x| repeat_bitmap(x, self.output_len))
493                            .as_ref(),
494                    );
495
496                    let arr =
497                        PrimitiveArray::<T::Native>::from_vec(out_vec).with_validity(leaf_validity);
498
499                    let (_, validities_lhs) = std::mem::take(&mut self.data_lhs);
500                    let (_, mut validities_rhs) = std::mem::take(&mut self.data_rhs);
501
502                    for v in validities_rhs.iter_mut() {
503                        if let Some(v) = v.as_mut() {
504                            *v = repeat_bitmap(v, self.output_len);
505                        }
506                    }
507
508                    finish_array_to_array_no_broadcast(
509                        std::mem::take(&mut self.output_name),
510                        &self.output_widths,
511                        self.output_len,
512                        &validities_lhs,
513                        &validities_rhs,
514                        Box::new(arr),
515                    )
516                },
517                (BinaryOpApplyType::ListToPrimitive, Broadcast::Left) => {
518                    let mut out_vec: Vec<T::Native> =
519                        Vec::with_capacity(self.output_len * self.stride);
520                    let out_ptr: *mut T::Native = out_vec.as_mut_ptr();
521                    let stride = self.stride;
522
523                    with_match_pl_num_arith!(&self.op.0, self.swapped, |$OP| {
524                        unsafe {
525                            for outer_idx in 0..self.output_len {
526                                let r = arr_rhs.value_unchecked(outer_idx);
527
528                                for inner_idx in 0..stride {
529                                    let l = arr_lhs.value_unchecked(inner_idx);
530
531                                    *out_ptr.add(stride * outer_idx + inner_idx) = $OP(l, r);
532                                }
533                            }
534                        }
535                    });
536
537                    unsafe { out_vec.set_len(self.output_len * self.stride) };
538
539                    let leaf_validity = combine_validities_array_to_primitive_no_broadcast(
540                        arr_lhs
541                            .validity()
542                            .map(|x| repeat_bitmap(x, self.output_len))
543                            .as_ref(),
544                        arr_rhs.validity(),
545                        self.stride,
546                    );
547
548                    let arr =
549                        PrimitiveArray::<T::Native>::from_vec(out_vec).with_validity(leaf_validity);
550
551                    let (_, mut validities) = std::mem::take(&mut self.data_lhs);
552
553                    for v in validities.iter_mut() {
554                        if let Some(v) = v.as_mut() {
555                            *v = repeat_bitmap(v, self.output_len);
556                        }
557                    }
558
559                    finish_with_level_validities(
560                        std::mem::take(&mut self.output_name),
561                        &self.output_widths,
562                        self.output_len,
563                        &validities,
564                        Box::new(arr),
565                    )
566                },
567                (BinaryOpApplyType::ListToPrimitive, Broadcast::NoBroadcast) => {
568                    let mut out_vec: Vec<T::Native> =
569                        Vec::with_capacity(self.output_len * self.stride);
570                    let out_ptr: *mut T::Native = out_vec.as_mut_ptr();
571                    let stride = self.stride;
572
573                    with_match_pl_num_arith!(&self.op.0, self.swapped, |$OP| {
574                        unsafe {
575                            for outer_idx in 0..self.output_len {
576                                let r = arr_rhs.value_unchecked(outer_idx);
577
578                                for inner_idx in 0..stride {
579                                    let idx = stride * outer_idx + inner_idx;
580                                    let l = arr_lhs.value_unchecked(idx);
581
582                                    *out_ptr.add(idx) = $OP(l, r);
583                                }
584                            }
585                        }
586                    });
587
588                    unsafe { out_vec.set_len(self.output_len * self.stride) };
589
590                    let leaf_validity = combine_validities_array_to_primitive_no_broadcast(
591                        arr_lhs.validity(),
592                        arr_rhs.validity(),
593                        self.stride,
594                    );
595
596                    let arr =
597                        PrimitiveArray::<T::Native>::from_vec(out_vec).with_validity(leaf_validity);
598
599                    let (_, validities) = std::mem::take(&mut self.data_lhs);
600
601                    finish_with_level_validities(
602                        std::mem::take(&mut self.output_name),
603                        &self.output_widths,
604                        self.output_len,
605                        &validities,
606                        Box::new(arr),
607                    )
608                },
609                (BinaryOpApplyType::ListToPrimitive, Broadcast::Right) => {
610                    assert_eq!(arr_rhs.len(), 1);
611
612                    let Some(r) = (unsafe { arr_rhs.get_unchecked(0) }) else {
613                        // RHS is single primitive NULL, create the result by setting the leaf validity to all-NULL.
614                        let (_, validities) = std::mem::take(&mut self.data_lhs);
615                        return finish_with_level_validities(
616                            std::mem::take(&mut self.output_name),
617                            &self.output_widths,
618                            self.output_len,
619                            &validities,
620                            Box::new(
621                                arr_lhs.clone().with_validity(Some(Bitmap::new_with_value(
622                                    false,
623                                    arr_lhs.len(),
624                                ))),
625                            ),
626                        );
627                    };
628
629                    let arr = self
630                        .op
631                        .0
632                        .apply_array_to_scalar::<T>(arr_lhs, r, self.swapped);
633
634                    let (_, validities) = std::mem::take(&mut self.data_lhs);
635
636                    finish_with_level_validities(
637                        std::mem::take(&mut self.output_name),
638                        &self.output_widths,
639                        self.output_len,
640                        &validities,
641                        Box::new(arr),
642                    )
643                },
644                v @ (BinaryOpApplyType::ListToList, Broadcast::NoBroadcast)
645                | v @ (BinaryOpApplyType::PrimitiveToList, Broadcast::Right)
646                | v @ (BinaryOpApplyType::ListToList, Broadcast::Left)
647                | v @ (BinaryOpApplyType::PrimitiveToList, Broadcast::Left)
648                | v @ (BinaryOpApplyType::PrimitiveToList, Broadcast::NoBroadcast) => {
649                    if cfg!(debug_assertions) {
650                        panic!("operation was not re-written: {v:?}")
651                    } else {
652                        unreachable!()
653                    }
654                },
655            }
656        }
657    }
658
659    /// Build the result of an array<->array operation.
660    #[inline(never)]
661    fn finish_array_to_array_no_broadcast(
662        output_name: PlSmallStr,
663        widths: &[usize],
664        outer_len: usize,
665        validities_lhs: &[Option<Bitmap>],
666        validities_rhs: &[Option<Bitmap>],
667        output_leaf_array: Box<dyn Array>,
668    ) -> ArrayChunked {
669        assert_eq!(
670            [widths.len(), validities_lhs.len(), validities_rhs.len()],
671            [widths.len(); 3]
672        );
673
674        let mut builder = FixedSizeListLevelBuilder::new(outer_len, widths);
675
676        let validities_iter = validities_lhs
677            .iter()
678            .zip(validities_rhs)
679            .map(|(l, r)| combine_validities_and(l.as_ref(), r.as_ref()));
680        // `.rev()` - we build this from the inner level.
681        let mut iter = widths.iter().zip(validities_iter).rev();
682
683        let mut out = {
684            let (width, opt_validity) = iter.next().unwrap();
685            builder.build_level(*width, opt_validity, output_leaf_array)
686        };
687
688        for (width, opt_validity) in iter {
689            out = builder.build_level(*width, opt_validity, Box::new(out))
690        }
691
692        ArrayChunked::with_chunk(output_name, out)
693    }
694
695    /// Used when we are operating between array<->primitive, as in that case we only need the
696    /// validities from the array side.
697    #[inline(never)]
698    fn finish_with_level_validities(
699        output_name: PlSmallStr,
700        widths: &[usize],
701        outer_len: usize,
702        validities: &[Option<Bitmap>],
703        output_leaf_array: Box<dyn Array>,
704    ) -> ArrayChunked {
705        assert_eq!(widths.len(), validities.len());
706
707        let mut builder = FixedSizeListLevelBuilder::new(outer_len, widths);
708
709        let validities_iter = validities.iter().cloned();
710        // `.rev()` - we build this from the inner level.
711        let mut iter = widths.iter().zip(validities_iter).rev();
712
713        let mut out = {
714            let (width, opt_validity) = iter.next().unwrap();
715            builder.build_level(*width, opt_validity, output_leaf_array)
716        };
717
718        for (width, opt_validity) in iter {
719            out = builder.build_level(*width, opt_validity, Box::new(out))
720        }
721
722        ArrayChunked::with_chunk(output_name, out)
723    }
724
725    /// ```text
726    /// array      [x, x, x, x, ..] (stride 2)
727    ///             | /   | /
728    ///             |/    |/
729    /// primitive  [x,    x,    ..]
730    /// ```
731    #[inline(never)]
732    fn combine_validities_array_to_primitive_no_broadcast(
733        array_leaf_validity: Option<&Bitmap>,
734        primitive_validity: Option<&Bitmap>,
735        stride: usize,
736    ) -> Option<Bitmap> {
737        match (array_leaf_validity, primitive_validity) {
738            (Some(l), Some(r)) => Some((l.clone().make_mut(), r)),
739            (Some(v), None) => return Some(v.clone()),
740            // Materialize a full-true validity to re-use the codepath, as we still
741            // need to spread the bits from the RHS to the correct positions.
742            (None, Some(v)) => Some((Bitmap::new_with_value(true, stride * v.len()).make_mut(), v)),
743            (None, None) => None,
744        }
745        .map(|(mut validity_out, primitive_validity)| {
746            assert_eq!(validity_out.len(), stride * primitive_validity.len());
747
748            unsafe {
749                for outer_idx in 0..primitive_validity.len() {
750                    let r = primitive_validity.get_bit_unchecked(outer_idx);
751
752                    for inner_idx in 0..stride {
753                        let idx = stride * outer_idx + inner_idx;
754                        let l = validity_out.get_unchecked(idx);
755
756                        validity_out.set_unchecked(idx, l & r);
757                    }
758                }
759            }
760
761            validity_out.freeze()
762        })
763    }
764
765    /// Returns `n_repeats` concatenated copies of the bitmap.
766    #[inline(never)]
767    fn repeat_bitmap(bitmap: &Bitmap, n_repeats: usize) -> Bitmap {
768        let mut out = BitmapBuilder::with_capacity(bitmap.len() * n_repeats);
769
770        for _ in 0..n_repeats {
771            for bit in bitmap.iter() {
772                unsafe { out.push_unchecked(bit) }
773            }
774        }
775
776        out.freeze()
777    }
778
779    struct FixedSizeListLevelBuilder {
780        heights: <Vec<usize> as IntoIterator>::IntoIter,
781    }
782
783    impl FixedSizeListLevelBuilder {
784        fn new(outer_len: usize, widths: &[usize]) -> Self {
785            let mut current_height = outer_len;
786            // We need to calculate heights here like this rather than dividing the stride because
787            // there can be 0-width arrays.
788            let mut heights = Vec::with_capacity(widths.len());
789
790            heights.push(current_height);
791            heights.extend(widths.iter().take(widths.len() - 1).map(|width| {
792                current_height *= *width;
793                current_height
794            }));
795
796            Self {
797                heights: heights.into_iter(),
798            }
799        }
800    }
801
802    impl FixedSizeListLevelBuilder {
803        fn build_level(
804            &mut self,
805            width: usize,
806            opt_validity: Option<Bitmap>,
807            inner_array: Box<dyn Array>,
808        ) -> FixedSizeListArray {
809            let level_height = self.heights.next_back().unwrap();
810            assert_eq!(inner_array.len(), level_height * width);
811
812            FixedSizeListArray::new(
813                ArrowDataType::FixedSizeList(
814                    Box::new(ArrowField::new(
815                        LIST_VALUES_NAME,
816                        inner_array.dtype().clone(),
817                        // is_nullable, we always set true otherwise the Eq kernels would panic
818                        // when they assert == on the arrow `Field`
819                        true,
820                    )),
821                    width,
822                ),
823                level_height,
824                inner_array,
825                opt_validity,
826            )
827        }
828    }
829}