Skip to main content

datafusion_functions_nested/
array_compact.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//! [`ScalarUDFImpl`] definitions for array_compact function.
6
7use crate::utils::{empty_list_values, make_scalar_function};
8use arrow::array::types::ByteArrayType;
9use arrow::array::{
10    Array, ArrayRef, ArrowPrimitiveType, AsArray, BooleanArray, BooleanBufferBuilder,
11    GenericByteArray, GenericListArray, OffsetSizeTrait, PrimitiveArray,
12    downcast_primitive_array,
13};
14use arrow::buffer::{BooleanBuffer, NullBuffer, OffsetBuffer};
15use arrow::compute::filter;
16use arrow::datatypes::DataType;
17use arrow::datatypes::DataType::{LargeList, List, Null};
18use datafusion_common::cast::as_generic_list_array;
19use datafusion_common::utils::offset_span_len;
20use datafusion_common::{Result, exec_err, utils::take_function_args};
21use datafusion_expr::{
22    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
23    Volatility,
24};
25use datafusion_macros::user_doc;
26use std::sync::Arc;
27
28make_udf_expr_and_func!(
29    ArrayCompact,
30    array_compact,
31    array,
32    "removes null values from the array.",
33    array_compact_udf
34);
35
36#[user_doc(
37    doc_section(label = "Array Functions"),
38    description = "Removes null values from the array.",
39    syntax_example = "array_compact(array)",
40    sql_example = r#"```sql
41> select array_compact([1, NULL, 2, NULL, 3]) arr;
42+-----------+
43| arr       |
44+-----------+
45| [1, 2, 3] |
46+-----------+
47```"#,
48    argument(
49        name = "array",
50        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
51    )
52)]
53#[derive(Debug, PartialEq, Eq, Hash)]
54pub struct ArrayCompact {
55    signature: Signature,
56    aliases: Vec<String>,
57}
58
59impl Default for ArrayCompact {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65impl ArrayCompact {
66    pub fn new() -> Self {
67        Self {
68            signature: Signature::array(Volatility::Immutable),
69            aliases: vec!["list_compact".to_string()],
70        }
71    }
72}
73
74impl ScalarUDFImpl for ArrayCompact {
75    fn name(&self) -> &str {
76        "array_compact"
77    }
78
79    fn signature(&self) -> &Signature {
80        &self.signature
81    }
82
83    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
84        Ok(arg_types[0].clone())
85    }
86
87    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
88        make_scalar_function(array_compact_inner)(&args.args)
89    }
90
91    fn aliases(&self) -> &[String] {
92        &self.aliases
93    }
94
95    fn documentation(&self) -> Option<&Documentation> {
96        self.doc()
97    }
98}
99
100/// array_compact SQL function
101fn array_compact_inner(arg: &[ArrayRef]) -> Result<ArrayRef> {
102    let [input_array] = take_function_args("array_compact", arg)?;
103
104    match &input_array.data_type() {
105        List(_) => compact_list::<i32>(input_array),
106        LargeList(_) => compact_list::<i64>(input_array),
107        Null => Ok(Arc::clone(input_array)),
108        array_type => exec_err!("array_compact does not support type '{array_type}'."),
109    }
110}
111
112/// Remove null elements from each row of a list array.
113///
114/// Each row is a range in a shared child array. Compaction removes null child
115/// values and rebuilds the row offsets, preserving null list rows.
116fn compact_list<O: OffsetSizeTrait>(input_array: &ArrayRef) -> Result<ArrayRef> {
117    let list_array = as_generic_list_array::<O>(input_array.as_ref())?;
118    let visible_len = offset_span_len(list_array.offsets());
119    if visible_len == 0 || list_array.null_count() == list_array.len() {
120        return Ok(Arc::clone(input_array));
121    }
122    // Restrict the child to the visible values before computing logical nulls,
123    // which can be expensive.
124    // Borrow fully visible values to avoid an Arc clone on the fast paths.
125    let values = list_array.values();
126    let start = list_array.offsets()[0].as_usize();
127    let sliced_values = (start != 0 || visible_len != values.len())
128        .then(|| values.slice(start, visible_len));
129    let values = sliced_values.as_ref().unwrap_or(values);
130    // Use logical nulls so element types without a validity buffer
131    // (e.g. NullArray) are still treated as null.
132    let Some(values_nulls) = values
133        .logical_nulls()
134        .filter(|nulls| nulls.null_count() != 0)
135    else {
136        return Ok(Arc::clone(input_array));
137    };
138    if values_nulls.null_count() == values_nulls.len() {
139        return Ok(empty_list_values(
140            list_array,
141            Arc::clone(list_array.value_field()),
142        ));
143    }
144
145    build_compacted_list(list_array, values.as_ref(), &values_nulls)
146}
147
148/// Copy primitive values while computing result row offsets. For other types,
149/// build row offsets and a keep bitmap, then copy variable-length strings/binary
150/// in valid spans or use Arrow's filter kernel for the remaining types.
151///
152/// `values` covers the visible range of list elements, and `values_nulls` is its
153/// logical validity. List offsets still index the original element array, so
154/// subtract the first list offset when indexing `values`.
155fn build_compacted_list<O: OffsetSizeTrait>(
156    list_array: &GenericListArray<O>,
157    values: &dyn Array,
158    values_nulls: &NullBuffer,
159) -> Result<ArrayRef> {
160    let (offsets, new_values) = downcast_primitive_array! {
161        values => Ok(compact_primitive(values, list_array, values_nulls)),
162        _ => compact_non_primitive(values, list_array, values_nulls),
163    }?;
164    Ok(Arc::new(GenericListArray::<O>::try_new(
165        Arc::clone(list_array.value_field()),
166        offsets,
167        new_values,
168        list_array.nulls().cloned(),
169    )?))
170}
171
172fn compact_primitive<T: ArrowPrimitiveType, O: OffsetSizeTrait>(
173    values: &PrimitiveArray<T>,
174    list_array: &GenericListArray<O>,
175    values_nulls: &NullBuffer,
176) -> (OffsetBuffer<O>, ArrayRef) {
177    let list_offsets = list_array.offsets();
178    let first_offset = list_offsets[0].as_usize();
179    let mut kept_values =
180        Vec::with_capacity(values_nulls.len() - values_nulls.null_count());
181    let mut offsets = Vec::with_capacity(list_array.len() + 1);
182    offsets.push(O::zero());
183    for (row, window) in list_offsets.windows(2).enumerate() {
184        if list_array.is_valid(row) {
185            let start = window[0].as_usize() - first_offset;
186            let end = window[1].as_usize() - first_offset;
187            for i in start..end {
188                if values_nulls.is_valid(i) {
189                    kept_values.push(values.value(i));
190                }
191            }
192        }
193        offsets.push(O::usize_as(kept_values.len()));
194    }
195    // Release capacity reserved for elements hidden by NULL list rows.
196    kept_values.shrink_to_fit();
197    let output = PrimitiveArray::<T>::new(kept_values.into(), None)
198        .with_data_type(values.data_type().clone());
199    (OffsetBuffer::new(offsets.into()), Arc::new(output))
200}
201
202fn compact_non_primitive<O: OffsetSizeTrait>(
203    values: &dyn Array,
204    list_array: &GenericListArray<O>,
205    values_nulls: &NullBuffer,
206) -> Result<(OffsetBuffer<O>, ArrayRef)> {
207    let list_offsets = list_array.offsets();
208    let first_offset = list_offsets[0].as_usize();
209    let mut offsets = Vec::with_capacity(list_array.len() + 1);
210    offsets.push(O::zero());
211    let mut kept_count = 0;
212    // Element validity is already the keep bitmap unless NULL rows hide elements.
213    let mut keep_mask =
214        (list_array.null_count() != 0).then(|| BooleanBufferBuilder::new(values.len()));
215    for (row, window) in list_offsets.windows(2).enumerate() {
216        let start = window[0].as_usize() - first_offset;
217        let len = window[1].as_usize() - window[0].as_usize();
218        if list_array.is_valid(row) {
219            let bit_start = values_nulls.offset() + start;
220            kept_count += values_nulls.buffer().count_set_bits_offset(bit_start, len);
221            if let Some(keep_mask) = &mut keep_mask {
222                // Skip elements belonging to preceding NULL rows.
223                keep_mask.resize(start);
224                keep_mask.append_packed_range(
225                    bit_start..bit_start + len,
226                    values_nulls.validity(),
227                );
228            }
229        }
230        offsets.push(O::usize_as(kept_count));
231    }
232    let keep_mask = keep_mask
233        .map(|mut keep_mask| {
234            keep_mask.resize(values.len());
235            keep_mask.finish()
236        })
237        .unwrap_or_else(|| values_nulls.inner().clone());
238    let output = match values.data_type() {
239        DataType::Utf8 => {
240            copy_byte_spans(values.as_string::<i32>(), &keep_mask, kept_count)
241        }
242        DataType::LargeUtf8 => {
243            copy_byte_spans(values.as_string::<i64>(), &keep_mask, kept_count)
244        }
245        DataType::Binary => {
246            copy_byte_spans(values.as_binary::<i32>(), &keep_mask, kept_count)
247        }
248        DataType::LargeBinary => {
249            copy_byte_spans(values.as_binary::<i64>(), &keep_mask, kept_count)
250        }
251        _ => filter(values, &BooleanArray::new(keep_mask, None))?,
252    };
253    Ok((OffsetBuffer::new(offsets.into()), output))
254}
255
256/// Copy spans of retained strings or binary values. The keep bitmap excludes
257/// NULL elements, so the output does not need a validity bitmap.
258fn copy_byte_spans<S: OffsetSizeTrait, T: ByteArrayType<Offset = S>>(
259    values: &GenericByteArray<T>,
260    keep_mask: &BooleanBuffer,
261    kept_count: usize,
262) -> ArrayRef {
263    let source_offsets = values.value_offsets();
264    let mut offsets = Vec::with_capacity(kept_count + 1);
265    offsets.push(S::zero());
266    let mut bytes = Vec::with_capacity(offset_span_len(values.offsets()));
267    for (start, end) in keep_mask.set_slices() {
268        let adjustment = S::usize_as(bytes.len()) - source_offsets[start];
269        offsets.extend(
270            source_offsets[start + 1..=end]
271                .iter()
272                .map(|offset| *offset + adjustment),
273        );
274        bytes.extend_from_slice(
275            &values.value_data()
276                [source_offsets[start].as_usize()..source_offsets[end].as_usize()],
277        );
278    }
279    // Release capacity reserved for bytes hidden by NULL elements or list rows.
280    bytes.shrink_to_fit();
281    // SAFETY: the keep bitmap selects only non-null elements, copied unchanged
282    // from the input. This preserves UTF-8 validity for string arrays. Rebasing
283    // offsets preserves their order, and the last offset equals bytes.len().
284    // The checked constructor would rescan unchanged bytes for UTF-8 validity.
285    let output = unsafe {
286        GenericByteArray::<T>::new_unchecked(
287            OffsetBuffer::new(offsets.into()),
288            bytes.into(),
289            None,
290        )
291    };
292    Arc::new(output)
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use arrow::array::{
299        AsArray, BinaryArray, BooleanArray, DictionaryArray, FixedSizeListArray,
300        Int32Array, ListArray, MapArray, NullArray, RunArray, StringArray,
301        StringViewArray, StructArray, UInt32Array, new_empty_array,
302    };
303    use arrow::compute::take;
304    use arrow::datatypes::{Field, Int32Type, TimeUnit};
305    use datafusion_common::utils::list_values;
306
307    #[test]
308    fn test_compact_child_types() -> Result<()> {
309        let input = Int32Array::from(vec![
310            Some(1),
311            None,
312            Some(2),  // Padding before the child slice.
313            Some(90), // Padding before the outer slice.
314            Some(10),
315            None,
316            Some(20),
317            Some(100),
318            Some(110), // Values belonging to a null list row.
319            None,
320            None, // A valid list with only null elements.
321            Some(30),
322            None,
323            Some(40),
324            Some(99), // Padding after the outer slice.
325        ]);
326        let mut children = vec![];
327        for data_type in [
328            DataType::UInt64,
329            DataType::Int32,
330            DataType::Float64,
331            DataType::Decimal256(40, 4),
332            DataType::Timestamp(TimeUnit::Microsecond, Some("America/Toronto".into())),
333            DataType::Dictionary(Box::new(DataType::UInt64), Box::new(DataType::Int32)),
334        ] {
335            children.push(arrow::compute::cast(&input, &data_type)?);
336        }
337        // Include empty/multibyte strings and nonempty storage behind nulls.
338        let strings = StringArray::from_iter_values(input.iter().map(|v| match v {
339            Some(10) => String::new(),
340            Some(v) => format!("café 🦀 {v}"),
341            None => "hidden null payload".to_string(),
342        }));
343        let strings = StringArray::new(
344            strings.offsets().clone(),
345            strings.values().clone(),
346            input.nulls().cloned(),
347        );
348        let binary = BinaryArray::from_iter(
349            input.iter().map(|v| v.map(|v| [0xff, v as u8, 0x80])),
350        );
351        children.extend([
352            Arc::new(BooleanArray::from_iter(
353                input.iter().map(|v| v.map(|v| v % 3 == 0)),
354            )) as ArrayRef,
355            Arc::new(strings.clone()),
356            arrow::compute::cast(&strings, &DataType::LargeUtf8)?,
357            Arc::new(binary.clone()),
358            arrow::compute::cast(&binary, &DataType::LargeBinary)?,
359            arrow::compute::cast(&binary, &DataType::BinaryView)?,
360            arrow::compute::cast(&binary, &DataType::FixedSizeBinary(3))?,
361            Arc::new(StringViewArray::from_iter(
362                input
363                    .iter()
364                    .map(|v| v.map(|v| format!("a longer string containing {v}"))),
365            )),
366            Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(
367                input.iter().map(|v| v.map(|v| vec![Some(v), None])),
368            )),
369            Arc::new(FixedSizeListArray::new(
370                Arc::new(Field::new_list_field(DataType::Int32, true)),
371                2,
372                Arc::new(Int32Array::from_iter(input.iter().flat_map(|v| [v, None]))),
373                input.nulls().cloned(),
374            )),
375            // Non-nullable struct fields may contain nulls masked by the struct.
376            Arc::new(StructArray::new(
377                vec![Field::new("value", DataType::Int32, false)].into(),
378                vec![Arc::new(input.clone())],
379                input.nulls().cloned(),
380            )),
381            // Non-null keys referring to null dictionary values are logical nulls.
382            Arc::new(DictionaryArray::<Int32Type>::try_new(
383                Int32Array::from_iter_values(0..input.len() as i32),
384                Arc::new(input.clone()),
385            )?),
386            // NULL keys can contain arbitrary indices; their validity must not
387            // be stripped before filtering the dictionary.
388            Arc::new(DictionaryArray::<Int32Type>::try_new(
389                Int32Array::new(
390                    input
391                        .iter()
392                        .enumerate()
393                        .map(|(i, value)| if value.is_some() { i as i32 } else { -1 })
394                        .collect::<Vec<_>>()
395                        .into(),
396                    input.nulls().cloned(),
397                ),
398                Arc::new(input.clone()),
399            )?),
400            Arc::new(RunArray::<Int32Type>::try_new(
401                &Int32Array::from_iter_values(1..=input.len() as i32),
402                &input,
403            )?),
404        ]);
405        let entries = StructArray::new(
406            vec![
407                Field::new("key", DataType::Int32, false),
408                Field::new("value", DataType::Int32, true),
409            ]
410            .into(),
411            vec![
412                Arc::new(Int32Array::from(vec![1; input.len()])),
413                Arc::new(input.clone()),
414            ],
415            None,
416        );
417        children.push(Arc::new(MapArray::new(
418            Arc::new(Field::new("entries", entries.data_type().clone(), false)),
419            OffsetBuffer::from_repeated_length(1, input.len()),
420            entries,
421            input.nulls().cloned(),
422            true,
423        )));
424        for child in children {
425            // Both child validity and outer-list validity have non-zero offsets.
426            let child = child.slice(3, 12);
427            let field = Arc::new(
428                Field::new_list_field(child.data_type().clone(), true)
429                    .with_metadata([("test".to_string(), "preserved".to_string())]),
430            );
431            let expected_values =
432                take(child.as_ref(), &UInt32Array::from(vec![1, 3, 8, 10]), None)?;
433            let input = ListArray::new(
434                Arc::clone(&field),
435                OffsetBuffer::from_lengths([1, 3, 0, 2, 2, 3, 1]),
436                child,
437                Some(NullBuffer::from(vec![
438                    true, true, true, false, true, true, true,
439                ])),
440            );
441            let expected = ListArray::new(
442                Arc::clone(&field),
443                OffsetBuffer::from_lengths([2, 0, 0, 0, 2]),
444                Arc::clone(&expected_values),
445                Some(NullBuffer::from(vec![true, true, false, true, true])),
446            );
447            for data_type in [input.data_type().clone(), LargeList(field)] {
448                let input = arrow::compute::cast(&input, &data_type)?.slice(1, 5);
449                let expected = arrow::compute::cast(&expected, &data_type)?;
450                let result = array_compact_inner(&[input])?;
451                assert_eq!(result.data_type(), &data_type);
452                assert_eq!(result.as_ref(), expected.as_ref(), "{data_type}");
453                // Also check that no hidden children of null parents were copied.
454                assert_eq!(
455                    list_values(result.as_ref())?.as_ref(),
456                    expected_values.as_ref(),
457                    "{data_type}"
458                );
459            }
460        }
461        Ok(())
462    }
463
464    #[test]
465    fn test_compact_byte_spans() -> Result<()> {
466        let rows = [
467            (true, vec![Some("outer padding")]),
468            (false, vec![Some("hidden leading")]),
469            (true, vec![Some("a"), Some("")]),
470            (true, vec![]),
471            (true, vec![Some("bc"), None, Some("é🦀"), Some("tail")]),
472            (false, vec![]),
473            (false, vec![Some("hidden"), Some("hidden")]),
474            (true, vec![Some(""), Some("終"), None]),
475            (false, vec![Some("hidden trailing")]),
476            (true, vec![Some("outer padding")]),
477        ];
478        let elements = std::iter::repeat_n(Some("element padding"), 3)
479            .chain(rows.iter().flat_map(|(_, row)| row.iter().copied()))
480            .collect::<Vec<_>>();
481        // Keep bytes behind NULL strings, and start the element bitmap mid-byte.
482        let strings = StringArray::from_iter_values(
483            elements.iter().map(|s| s.unwrap_or("hidden NULL bytes")),
484        );
485        let strings = StringArray::new(
486            strings.offsets().clone(),
487            strings.values().clone(),
488            Some(NullBuffer::from_iter(elements.iter().map(Option::is_some))),
489        )
490        .slice(3, elements.len() - 3);
491        let expected_strings =
492            StringArray::from(vec!["a", "", "bc", "é🦀", "tail", "", "終"]);
493        for data_type in [
494            DataType::Utf8,
495            DataType::LargeUtf8,
496            DataType::Binary,
497            DataType::LargeBinary,
498        ] {
499            let values = arrow::compute::cast(&strings, &data_type)?;
500            let expected_values = arrow::compute::cast(&expected_strings, &data_type)?;
501            let field = Arc::new(Field::new_list_field(data_type, true));
502            let input = ListArray::new(
503                Arc::clone(&field),
504                OffsetBuffer::from_lengths(rows.iter().map(|(_, row)| row.len())),
505                values,
506                Some(NullBuffer::from_iter(rows.iter().map(|(valid, _)| *valid))),
507            )
508            .slice(1, 8);
509            // The first span crosses a row boundary and an empty row. NULL rows
510            // must break spans even when they contain non-NULL strings.
511            let expected = ListArray::new(
512                Arc::clone(&field),
513                OffsetBuffer::from_lengths([0, 2, 0, 3, 0, 0, 2, 0]),
514                expected_values,
515                input.nulls().cloned(),
516            );
517            for data_type in [input.data_type().clone(), LargeList(field)] {
518                let input = arrow::compute::cast(&input, &data_type)?;
519                let expected = arrow::compute::cast(&expected, &data_type)?;
520                let result = array_compact_inner(&[input])?;
521                result.to_data().validate_full()?;
522                assert_eq!(result.as_ref(), expected.as_ref());
523                assert_eq!(
524                    list_values(result.as_ref())?.to_data(),
525                    list_values(expected.as_ref())?.to_data()
526                );
527            }
528        }
529        Ok(())
530    }
531
532    #[test]
533    fn test_compact_nested_rows() -> Result<()> {
534        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
535        let child = ListArray::new(
536            Arc::clone(&field),
537            OffsetBuffer::from_repeated_length(2, 8),
538            Arc::new(Int32Array::from_iter(
539                (0..16).map(|i| (i % 2 == 0).then_some(i)),
540            )),
541            Some(NullBuffer::from(vec![
542                true, true, false, true, true, true, true, true,
543            ])),
544        );
545        for child_type in [child.data_type().clone(), LargeList(field)] {
546            let child = arrow::compute::cast(&child, &child_type)?;
547            let expected = take(
548                child.as_ref(),
549                &UInt32Array::from(vec![0, 1, 3, 4, 7]),
550                None,
551            )?;
552            let field = Arc::new(Field::new_list_field(child_type, true));
553            // An empty row separates adjacent selected children. The null
554            // parent has a nonempty range of children that must be skipped.
555            let input = ListArray::new(
556                Arc::clone(&field),
557                OffsetBuffer::from_lengths([1, 0, 2, 2, 2, 1]),
558                child,
559                Some(NullBuffer::from(vec![true, true, true, true, false, true])),
560            );
561            for data_type in [input.data_type().clone(), LargeList(field)] {
562                let arg = arrow::compute::cast(&input, &data_type)?;
563                let result = array_compact_inner(&[arg])?;
564                assert_eq!(result.data_type(), &data_type);
565                assert_eq!(result.nulls(), input.nulls());
566                let result = arrow::compute::cast(&result, input.data_type())?;
567                let list = result.as_list::<i32>();
568                assert_eq!(list.value_offsets(), &[0, 1, 1, 2, 4, 4, 5]);
569                assert_eq!(list.values().as_ref(), expected.as_ref());
570            }
571        }
572        Ok(())
573    }
574
575    #[test]
576    fn test_compact_all_null_children() -> Result<()> {
577        let children: Vec<ArrayRef> = vec![
578            Arc::new(Int32Array::new_null(5)),
579            Arc::new(NullArray::new(5)),
580            Arc::new(DictionaryArray::<Int32Type>::try_new(
581                Int32Array::from(vec![0; 5]),
582                Arc::new(Int32Array::new_null(1)),
583            )?),
584            Arc::new(RunArray::<Int32Type>::try_new(
585                &Int32Array::from(vec![5]),
586                &Int32Array::new_null(1),
587            )?),
588        ];
589        for child in children {
590            let field = Arc::new(
591                Field::new_list_field(child.data_type().clone(), true)
592                    .with_metadata([("test".to_string(), "preserved".to_string())]),
593            );
594            let nulls = Some(NullBuffer::from(vec![true, false, true]));
595            let input = ListArray::new(
596                Arc::clone(&field),
597                OffsetBuffer::from_lengths([2, 0, 3]),
598                child,
599                nulls.clone(),
600            );
601            let expected = ListArray::new(
602                Arc::clone(&field),
603                OffsetBuffer::new_zeroed(3),
604                new_empty_array(field.data_type()),
605                nulls.clone(),
606            );
607            for data_type in [input.data_type().clone(), LargeList(field)] {
608                let input = arrow::compute::cast(&input, &data_type)?;
609                let expected = arrow::compute::cast(&expected, &data_type)?;
610                assert_eq!(array_compact_inner(&[input])?.as_ref(), expected.as_ref());
611            }
612        }
613        Ok(())
614    }
615
616    #[test]
617    fn test_compact_null_row_capacity() -> Result<()> {
618        let padding = 8192;
619        let values = Int32Array::from_iter(
620            std::iter::repeat_n(Some(1), padding)
621                .chain([Some(2), None, Some(3)])
622                .chain(std::iter::repeat_n(Some(1), padding)),
623        );
624        for data_type in [DataType::Int32, DataType::Utf8, DataType::LargeUtf8] {
625            let values = arrow::compute::cast(&values, &data_type)?;
626            let expected =
627                arrow::compute::cast(&Int32Array::from(vec![2, 3]), &data_type)?;
628            let field = Arc::new(Field::new_list_field(data_type, true));
629            let input = ListArray::new(
630                Arc::clone(&field),
631                OffsetBuffer::from_lengths([padding, 3, padding]),
632                values,
633                Some(NullBuffer::from(vec![false, true, false])),
634            );
635            for list_type in [input.data_type().clone(), LargeList(field)] {
636                let input = arrow::compute::cast(&input, &list_type)?;
637                let result = array_compact_inner(&[input])?;
638                assert_eq!(list_values(result.as_ref())?.as_ref(), expected.as_ref());
639                assert!(result.get_buffer_memory_size() < 1024);
640            }
641        }
642        Ok(())
643    }
644
645    #[test]
646    fn test_sliced_capacity() -> Result<()> {
647        crate::utils::tests::check_sliced_list_behavior(|input| {
648            array_compact_inner(std::slice::from_ref(input))
649        })
650    }
651
652    #[test]
653    fn test_compact_hidden_nulls_zero_copy() -> Result<()> {
654        let primitive =
655            Int32Array::from(vec![None, Some(10), Some(20), None, Some(30), None]);
656        let dictionary = DictionaryArray::<Int32Type>::try_new(
657            Int32Array::from(vec![0, 1, 2, 3, 4, 5]),
658            Arc::new(primitive.clone()),
659        )?;
660        let runs = RunArray::<Int32Type>::try_new(
661            &Int32Array::from(vec![1, 2, 3, 4, 5, 6]),
662            &primitive,
663        )?;
664        for values in [
665            Arc::new(primitive) as ArrayRef,
666            Arc::new(dictionary),
667            Arc::new(runs),
668        ] {
669            let field = Arc::new(Field::new_list_field(values.data_type().clone(), true));
670            let input = ListArray::new(
671                Arc::clone(&field),
672                OffsetBuffer::from_lengths([1, 2, 2, 1]),
673                values,
674                None,
675            );
676            for data_type in [input.data_type().clone(), LargeList(field)] {
677                // Nulls outside the selected row must not prevent the zero-copy fast path.
678                let sliced = arrow::compute::cast(&input, &data_type)?.slice(1, 1);
679                let result = array_compact_inner(std::slice::from_ref(&sliced))?;
680                assert!(Arc::ptr_eq(&result, &sliced));
681            }
682        }
683        Ok(())
684    }
685}