Skip to main content

datafusion_common/utils/
mod.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//! This module provides the bisect function, which implements binary search.
6
7pub(crate) mod aggregate;
8pub mod expr;
9pub mod hex;
10pub mod memory;
11pub mod proxy;
12pub mod string_utils;
13
14use crate::assert_or_internal_err;
15use crate::error::{
16    _exec_datafusion_err, _exec_err, _internal_datafusion_err, _plan_datafusion_err,
17};
18use crate::{Result, ScalarValue};
19use arrow::array::{
20    Array, ArrayRef, FixedSizeListArray, LargeListArray, ListArray, OffsetSizeTrait,
21    cast::AsArray,
22};
23use arrow::array::{
24    ArrowPrimitiveType, BooleanArray, Datum, GenericListArray, Int32Array, Int64Array,
25    MutableArrayData, PrimitiveArray, layout, make_array,
26};
27use arrow::array::{LargeListViewArray, ListViewArray};
28use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
29use arrow::compute::kernels::cmp::eq;
30use arrow::compute::kernels::length::length;
31use arrow::compute::{SortColumn, SortOptions, nullif, partition};
32use arrow::datatypes::{
33    ArrowNativeType, DataType, Field, Int32Type, Int64Type, Metadata, SchemaRef,
34};
35#[cfg(feature = "sql")]
36use sqlparser::{ast::Ident, dialect::GenericDialect, parser::Parser};
37use std::borrow::{Borrow, Cow};
38use std::cmp::{Ordering, min};
39use std::collections::HashSet;
40use std::iter::repeat_n;
41use std::num::NonZero;
42use std::ops::Range;
43use std::sync::{Arc, LazyLock};
44use std::thread::available_parallelism;
45
46/// Applies an optional projection to a [`SchemaRef`], returning the
47/// projected schema
48///
49/// Example:
50/// ```
51/// use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
52/// use datafusion_common::project_schema;
53///
54/// // Schema with columns 'a', 'b', and 'c'
55/// let schema = SchemaRef::new(Schema::new(vec![
56///     Field::new("a", DataType::Int32, true),
57///     Field::new("b", DataType::Int64, true),
58///     Field::new("c", DataType::Utf8, true),
59/// ]));
60///
61/// // Pick columns 'c' and 'b'
62/// let projection = Some(vec![2, 1]);
63/// let projected_schema = project_schema(&schema, projection.as_ref()).unwrap();
64///
65/// let expected_schema = SchemaRef::new(Schema::new(vec![
66///     Field::new("c", DataType::Utf8, true),
67///     Field::new("b", DataType::Int64, true),
68/// ]));
69///
70/// assert_eq!(projected_schema, expected_schema);
71/// ```
72pub fn project_schema<T: AsRef<[usize]> + ?Sized>(
73    schema: &SchemaRef,
74    projection: Option<&T>,
75) -> Result<SchemaRef> {
76    let schema = match projection {
77        Some(columns) => Arc::new(schema.project(columns.as_ref())?),
78        None => Arc::clone(schema),
79    };
80    Ok(schema)
81}
82
83/// Extracts a row at the specified index from a set of columns and stores it in the provided buffer.
84pub fn extract_row_at_idx_to_buf(
85    columns: &[ArrayRef],
86    idx: usize,
87    buf: &mut Vec<ScalarValue>,
88) -> Result<()> {
89    buf.clear();
90
91    let iter = columns
92        .iter()
93        .map(|arr| ScalarValue::try_from_array(arr, idx));
94    for v in iter.into_iter() {
95        buf.push(v?);
96    }
97
98    Ok(())
99}
100/// Given column vectors, returns row at `idx`.
101pub fn get_row_at_idx(columns: &[ArrayRef], idx: usize) -> Result<Vec<ScalarValue>> {
102    columns
103        .iter()
104        .map(|arr| ScalarValue::try_from_array(arr, idx))
105        .collect()
106}
107
108/// This function compares two tuples depending on the given sort options.
109pub fn compare_rows(
110    x: &[ScalarValue],
111    y: &[ScalarValue],
112    sort_options: &[SortOptions],
113) -> Result<Ordering> {
114    let zip_it = x.iter().zip(y.iter()).zip(sort_options.iter());
115    // Preserving lexical ordering.
116    for ((lhs, rhs), sort_options) in zip_it {
117        // Consider all combinations of NULLS FIRST/LAST and ASC/DESC configurations.
118        let result = match (lhs.is_null(), rhs.is_null(), sort_options.nulls_first) {
119            (true, false, false) | (false, true, true) => Ordering::Greater,
120            (true, false, true) | (false, true, false) => Ordering::Less,
121            (false, false, _) => {
122                if sort_options.descending {
123                    rhs.try_cmp(lhs)?
124                } else {
125                    lhs.try_cmp(rhs)?
126                }
127            }
128            (true, true, _) => continue,
129        };
130        if result != Ordering::Equal {
131            return Ok(result);
132        }
133    }
134    Ok(Ordering::Equal)
135}
136
137/// This function searches for a tuple of given values (`target`) among the given
138/// rows (`item_columns`) using the bisection algorithm. It assumes that `item_columns`
139/// is sorted according to `sort_options` and returns the insertion index of `target`.
140/// Template argument `SIDE` being `true`/`false` means left/right insertion.
141pub fn bisect<const SIDE: bool>(
142    item_columns: &[ArrayRef],
143    target: &[ScalarValue],
144    sort_options: &[SortOptions],
145) -> Result<usize> {
146    let low: usize = 0;
147    let high: usize = item_columns
148        .first()
149        .ok_or_else(|| _internal_datafusion_err!("Column array shouldn't be empty"))?
150        .len();
151    let compare_fn = |current: &[ScalarValue], target: &[ScalarValue]| {
152        let cmp = compare_rows(current, target, sort_options)?;
153        Ok(if SIDE { cmp.is_lt() } else { cmp.is_le() })
154    };
155    find_bisect_point(item_columns, target, compare_fn, low, high)
156}
157
158/// This function searches for a tuple of given values (`target`) among a slice of
159/// the given rows (`item_columns`) using the bisection algorithm. The slice starts
160/// at the index `low` and ends at the index `high`. The boolean-valued function
161/// `compare_fn` specifies whether we bisect on the left (by returning `false`),
162/// or on the right (by returning `true`) when we compare the target value with
163/// the current value as we iteratively bisect the input.
164pub fn find_bisect_point<F>(
165    item_columns: &[ArrayRef],
166    target: &[ScalarValue],
167    compare_fn: F,
168    mut low: usize,
169    mut high: usize,
170) -> Result<usize>
171where
172    F: Fn(&[ScalarValue], &[ScalarValue]) -> Result<bool>,
173{
174    let mut val = Vec::with_capacity(item_columns.len());
175    while low < high {
176        let mid = ((high - low) / 2) + low;
177        extract_row_at_idx_to_buf(item_columns, mid, &mut val)?;
178        if compare_fn(&val, target)? {
179            low = mid + 1;
180        } else {
181            high = mid;
182        }
183    }
184    Ok(low)
185}
186
187/// This function searches for a tuple of given values (`target`) among the given
188/// rows (`item_columns`) via a linear scan. It assumes that `item_columns` is sorted
189/// according to `sort_options` and returns the insertion index of `target`.
190/// Template argument `SIDE` being `true`/`false` means left/right insertion.
191pub fn linear_search<const SIDE: bool>(
192    item_columns: &[ArrayRef],
193    target: &[ScalarValue],
194    sort_options: &[SortOptions],
195) -> Result<usize> {
196    let low: usize = 0;
197    let high: usize = item_columns
198        .first()
199        .ok_or_else(|| _internal_datafusion_err!("Column array shouldn't be empty"))?
200        .len();
201    let compare_fn = |current: &[ScalarValue], target: &[ScalarValue]| {
202        let cmp = compare_rows(current, target, sort_options)?;
203        Ok(if SIDE { cmp.is_lt() } else { cmp.is_le() })
204    };
205    search_in_slice(item_columns, target, compare_fn, low, high)
206}
207
208/// This function searches for a tuple of given values (`target`) among a slice of
209/// the given rows (`item_columns`) via a linear scan. The slice starts at the index
210/// `low` and ends at the index `high`. The boolean-valued function `compare_fn`
211/// specifies the stopping criterion.
212pub fn search_in_slice<F>(
213    item_columns: &[ArrayRef],
214    target: &[ScalarValue],
215    compare_fn: F,
216    mut low: usize,
217    high: usize,
218) -> Result<usize>
219where
220    F: Fn(&[ScalarValue], &[ScalarValue]) -> Result<bool>,
221{
222    let mut val = Vec::new();
223    while low < high {
224        extract_row_at_idx_to_buf(item_columns, low, &mut val)?;
225        if !compare_fn(&val, target)? {
226            break;
227        }
228        low += 1;
229    }
230    Ok(low)
231}
232
233/// Given a list of 0 or more already sorted columns, finds the
234/// partition ranges that would partition equally across columns.
235///
236/// See [`partition`] for more details.
237pub fn evaluate_partition_ranges(
238    num_rows: usize,
239    partition_columns: &[SortColumn],
240) -> Result<Vec<Range<usize>>> {
241    Ok(if partition_columns.is_empty() {
242        vec![Range {
243            start: 0,
244            end: num_rows,
245        }]
246    } else {
247        let cols: Vec<_> = partition_columns
248            .iter()
249            .map(|x| Arc::clone(&x.values))
250            .collect();
251        partition(&cols)?.ranges()
252    })
253}
254
255/// Wraps identifier string in double quotes, escaping any double quotes in
256/// the identifier by replacing it with two double quotes
257///
258/// e.g. identifier `tab.le"name` becomes `"tab.le""name"`
259pub fn quote_identifier(s: &str) -> Cow<'_, str> {
260    if needs_quotes(s) {
261        Cow::Owned(format!("\"{}\"", s.replace('"', "\"\"")))
262    } else {
263        Cow::Borrowed(s)
264    }
265}
266
267/// returns true if this identifier needs quotes
268fn needs_quotes(s: &str) -> bool {
269    let mut chars = s.chars();
270
271    // first char can not be a number unless escaped
272    if let Some(first_char) = chars.next()
273        && !(first_char.is_ascii_lowercase() || first_char == '_')
274    {
275        return true;
276    }
277
278    !chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
279}
280
281#[cfg(feature = "sql")]
282pub(crate) fn parse_identifiers(s: &str) -> Result<Vec<Ident>> {
283    let dialect = GenericDialect;
284    let mut parser = Parser::new(&dialect).try_with_sql(s)?;
285    let idents = parser.parse_multipart_identifier()?;
286    Ok(idents)
287}
288
289/// Parse a string into a vector of identifiers.
290///
291/// Note: If ignore_case is false, the string will be normalized to lowercase.
292#[cfg(feature = "sql")]
293pub(crate) fn parse_identifiers_normalized(s: &str, ignore_case: bool) -> Vec<String> {
294    parse_identifiers(s)
295        .unwrap_or_default()
296        .into_iter()
297        .map(|id| match id.quote_style {
298            Some(_) => id.value,
299            None if ignore_case => id.value,
300            _ => id.value.to_ascii_lowercase(),
301        })
302        .collect::<Vec<_>>()
303}
304
305#[cfg(not(feature = "sql"))]
306pub(crate) fn parse_identifiers(s: &str) -> Result<Vec<String>> {
307    let mut result = Vec::new();
308    let mut current = String::new();
309    let mut in_quotes = false;
310
311    for ch in s.chars() {
312        match ch {
313            '"' => {
314                in_quotes = !in_quotes;
315                current.push(ch);
316            }
317            '.' if !in_quotes => {
318                result.push(current.clone());
319                current.clear();
320            }
321            _ => {
322                current.push(ch);
323            }
324        }
325    }
326
327    // Push the last part if it's not empty
328    if !current.is_empty() {
329        result.push(current);
330    }
331
332    Ok(result)
333}
334
335#[cfg(not(feature = "sql"))]
336pub(crate) fn parse_identifiers_normalized(s: &str, ignore_case: bool) -> Vec<String> {
337    parse_identifiers(s)
338        .unwrap_or_default()
339        .into_iter()
340        .map(|id| {
341            let is_double_quoted = if id.len() > 2 {
342                let mut chars = id.chars();
343                chars.next() == Some('"') && chars.last() == Some('"')
344            } else {
345                false
346            };
347            if is_double_quoted {
348                id[1..id.len() - 1].replace("\"\"", "\"")
349            } else if ignore_case {
350                id
351            } else {
352                id.to_ascii_lowercase()
353            }
354        })
355        .collect::<Vec<_>>()
356}
357
358/// This function "takes" the elements at `indices` from the slice `items`.
359pub fn get_at_indices<T: Clone, I: Borrow<usize>>(
360    items: &[T],
361    indices: impl IntoIterator<Item = I>,
362) -> Result<Vec<T>> {
363    indices
364        .into_iter()
365        .map(|idx| items.get(*idx.borrow()).cloned())
366        .collect::<Option<Vec<T>>>()
367        .ok_or_else(|| {
368            _exec_datafusion_err!("Expects indices to be in the range of searched vector")
369        })
370}
371
372/// This function finds the longest prefix of the form 0, 1, 2, ... within the
373/// collection `sequence`. Examples:
374/// - For 0, 1, 2, 4, 5; we would produce 3, meaning 0, 1, 2 is the longest satisfying
375///   prefix.
376/// - For 1, 2, 3, 4; we would produce 0, meaning there is no such prefix.
377pub fn longest_consecutive_prefix<T: Borrow<usize>>(
378    sequence: impl IntoIterator<Item = T>,
379) -> usize {
380    let mut count = 0;
381    for item in sequence {
382        if !count.eq(item.borrow()) {
383            break;
384        }
385        count += 1;
386    }
387    count
388}
389
390/// Splits `vec` at index `n`, returning the first `n` elements and leaving the
391/// remaining `vec.len() - n` elements in `vec`.
392///
393/// Allocates for whichever side is smaller, so the new allocation is
394/// `min(n, vec.len() - n)` rather than always `n` (as `vec.drain(0..n).collect()`
395/// would). This matters when the split emits a prefix under memory pressure,
396/// where `n` can be close to `vec.len()`.
397pub fn split_vec_min_alloc<T>(vec: &mut Vec<T>, n: usize) -> Vec<T> {
398    if n * 2 <= vec.len() {
399        vec.drain(0..n).collect()
400    } else {
401        let remaining = vec.split_off(n);
402        std::mem::replace(vec, remaining)
403    }
404}
405
406#[cfg(test)]
407mod split_vec_min_alloc_tests {
408    use super::split_vec_min_alloc;
409
410    #[test]
411    fn drain_branch() {
412        // n * 2 <= len  ->  drain+collect branch (allocates n elements)
413        let mut v = vec![1, 2, 3, 4, 5, 6];
414        let first = split_vec_min_alloc(&mut v, 2);
415        assert_eq!(first, vec![1, 2]);
416        assert_eq!(v, vec![3, 4, 5, 6]);
417    }
418
419    #[test]
420    fn split_off_branch() {
421        // remaining < n  ->  split_off+replace branch (allocates remaining elements)
422        let mut v = vec![1, 2, 3, 4, 5, 6];
423        let first = split_vec_min_alloc(&mut v, 4);
424        assert_eq!(first, vec![1, 2, 3, 4]);
425        assert_eq!(v, vec![5, 6]);
426    }
427
428    #[test]
429    fn exactly_half() {
430        // n * 2 == len  ->  drain branch (boundary)
431        let mut v = vec![1, 2, 3, 4];
432        let first = split_vec_min_alloc(&mut v, 2);
433        assert_eq!(first, vec![1, 2]);
434        assert_eq!(v, vec![3, 4]);
435    }
436
437    #[test]
438    fn take_all() {
439        let mut v = vec![1, 2, 3];
440        let first = split_vec_min_alloc(&mut v, 3);
441        assert_eq!(first, vec![1, 2, 3]);
442        assert!(v.is_empty());
443    }
444
445    #[test]
446    fn take_none() {
447        let mut v = vec![1, 2, 3];
448        let first = split_vec_min_alloc(&mut v, 0);
449        assert!(first.is_empty());
450        assert_eq!(v, vec![1, 2, 3]);
451    }
452
453    #[test]
454    fn emitted_prefix_does_not_realloc_on_push() {
455        // Demonstrates *why* the split-off branch must NOT call `shrink_to_fit`.
456        //
457        // Downstream callers (e.g. `multi_group_by/bytes.rs`, which does
458        // `first_n_offsets.push(offset_n)` right after the split) push onto the
459        // emitted prefix immediately. The split-off branch hands the original
460        // backing allocation to that prefix, so the prefix already has spare
461        // capacity for the very next push.
462        //
463        // If we shrank the prefix to fit, that next push would have to
464        // reallocate, and Vec's growth strategy would land it at a *larger*
465        // capacity than the original allocation we started with -- the opposite
466        // of the memory saving `shrink_to_fit` was meant to deliver.
467
468        // A Vec with a known, deliberately large capacity. n*2 > len, so this
469        // takes the split-off branch.
470        let mut v: Vec<u32> = Vec::with_capacity(64);
471        v.extend(0..10);
472        let original_capacity = v.capacity();
473        assert!(original_capacity >= 64);
474
475        // Emit a prefix that is most of the Vec (n = 8, remaining = 2).
476        let mut prefix = split_vec_min_alloc(&mut v, 8);
477        assert_eq!(prefix, vec![0, 1, 2, 3, 4, 5, 6, 7]);
478
479        // The split-off branch moved the original backing store into `prefix`,
480        // so it keeps the original (large) capacity -- no shrink happened.
481        assert_eq!(
482            prefix.capacity(),
483            original_capacity,
484            "split-off branch must hand the original allocation to the prefix"
485        );
486
487        // The caller's very next operation: push one element onto the prefix.
488        prefix.push(99);
489
490        // Because the capacity was preserved, the push reused the existing
491        // allocation: post-push capacity is unchanged and still <= original.
492        // This is the realloc that `shrink_to_fit` would have forced.
493        assert_eq!(
494            prefix.capacity(),
495            original_capacity,
496            "push must reuse the preserved allocation (no realloc)"
497        );
498        assert!(prefix.capacity() <= original_capacity);
499
500        // Counter-demonstration: had we shrunk the prefix to fit (capacity 8),
501        // the same push would have reallocated. Vec doubles on growth, so the
502        // post-push capacity (16) ends up LARGER than where a length-8 prefix
503        // started -- and we paid a realloc for it.
504        let mut shrunk: Vec<u32> = prefix[..8].to_vec();
505        shrunk.shrink_to_fit();
506        let shrunk_capacity = shrink_then_push_capacity(&mut shrunk);
507        assert!(
508            shrunk_capacity > 8,
509            "shrink-to-fit then push reallocates to a larger capacity"
510        );
511    }
512
513    /// Helper for the counter-demonstration above: push one element and report
514    /// the resulting capacity.
515    fn shrink_then_push_capacity(v: &mut Vec<u32>) -> usize {
516        v.push(99);
517        v.capacity()
518    }
519}
520
521/// Creates single element [`ListArray`], [`LargeListArray`] and
522/// [`FixedSizeListArray`] from other arrays
523///
524/// For example this builder can convert `[1, 2, 3]` into `[[1, 2, 3]]`
525///
526/// # Example
527/// ```
528/// # use std::sync::Arc;
529/// # use arrow::array::{Array, ListArray};
530/// # use arrow::array::types::Int64Type;
531/// # use datafusion_common::utils::SingleRowListArrayBuilder;
532/// // Array is [1, 2, 3]
533/// let arr = ListArray::from_iter_primitive::<Int64Type, _, _>(vec![Some(vec![
534///     Some(1),
535///     Some(2),
536///     Some(3),
537/// ])]);
538/// // Wrap as a list array: [[1, 2, 3]]
539/// let list_arr = SingleRowListArrayBuilder::new(Arc::new(arr)).build_list_array();
540/// assert_eq!(list_arr.len(), 1);
541/// ```
542#[derive(Debug, Clone)]
543pub struct SingleRowListArrayBuilder {
544    /// array to be wrapped
545    arr: ArrayRef,
546    /// Should the resulting array be nullable? Defaults to `true`.
547    nullable: bool,
548    /// Specify the field name for the resulting array. Defaults to value used in
549    /// [`Field::new_list_field`]
550    field_name: Option<String>,
551    field_metadata: Metadata,
552}
553
554impl SingleRowListArrayBuilder {
555    /// Create a new instance of [`SingleRowListArrayBuilder`]
556    pub fn new(arr: ArrayRef) -> Self {
557        Self {
558            arr,
559            nullable: true,
560            field_name: None,
561            field_metadata: Metadata::default(),
562        }
563    }
564
565    /// Set the nullable flag
566    pub fn with_nullable(mut self, nullable: bool) -> Self {
567        self.nullable = nullable;
568        self
569    }
570
571    /// sets the field name for the resulting array
572    pub fn with_field_name(mut self, field_name: Option<String>) -> Self {
573        self.field_name = field_name;
574        self
575    }
576
577    /// Copies field name, nullability, and metadata from the specified field
578    pub fn with_field(mut self, field: &Field) -> Self {
579        self.field_name = Some(field.name().to_owned());
580        self.nullable = field.is_nullable();
581        self.field_metadata = field.metadata().clone();
582        self
583    }
584
585    /// Build a single element [`ListArray`]
586    pub fn build_list_array(self) -> ListArray {
587        let (field, arr) = self.into_field_and_arr();
588        let offsets = OffsetBuffer::from_lengths([arr.len()]);
589        ListArray::new(field, offsets, arr, None)
590    }
591
592    /// Build a single element [`ListArray`] and wrap as [`ScalarValue::List`]
593    pub fn build_list_scalar(self) -> ScalarValue {
594        ScalarValue::List(Arc::new(self.build_list_array()))
595    }
596
597    /// Build a single element [`LargeListArray`]
598    pub fn build_large_list_array(self) -> LargeListArray {
599        let (field, arr) = self.into_field_and_arr();
600        let offsets = OffsetBuffer::from_lengths([arr.len()]);
601        LargeListArray::new(field, offsets, arr, None)
602    }
603
604    /// Build a single element [`LargeListArray`] and wrap as [`ScalarValue::LargeList`]
605    pub fn build_large_list_scalar(self) -> ScalarValue {
606        ScalarValue::LargeList(Arc::new(self.build_large_list_array()))
607    }
608
609    /// Build a single element [`FixedSizeListArray`]
610    pub fn build_fixed_size_list_array(self, list_size: usize) -> FixedSizeListArray {
611        let (field, arr) = self.into_field_and_arr();
612        FixedSizeListArray::try_new_with_length(field, list_size as i32, arr, None, 1)
613            .unwrap()
614    }
615
616    /// Build a single element [`FixedSizeListArray`] and wrap as [`ScalarValue::FixedSizeList`]
617    pub fn build_fixed_size_list_scalar(self, list_size: usize) -> ScalarValue {
618        ScalarValue::FixedSizeList(Arc::new(self.build_fixed_size_list_array(list_size)))
619    }
620
621    /// Build a single element [`ListViewArray`]
622    pub fn build_list_view_array(self) -> ListViewArray {
623        let (field, arr) = self.into_field_and_arr();
624        let offsets = ScalarBuffer::from(vec![0]);
625        let sizes = ScalarBuffer::from(vec![i32::try_from(arr.len()).expect(
626            "Trying to construct a ListView where element length exceeds i32::MAX",
627        )]);
628        ListViewArray::new(field, offsets, sizes, arr, None)
629    }
630
631    /// Build a single element [`ListViewArray`] and wrap as [`ScalarValue::ListView`]
632    pub fn build_list_view_scalar(self) -> ScalarValue {
633        ScalarValue::ListView(Arc::new(self.build_list_view_array()))
634    }
635
636    /// Build a single element [`LargeListViewArray`]
637    pub fn build_large_list_view_array(self) -> LargeListViewArray {
638        let (field, arr) = self.into_field_and_arr();
639        let offsets = ScalarBuffer::from(vec![0]);
640        let sizes = ScalarBuffer::from(vec![arr.len() as i64]);
641        LargeListViewArray::new(field, offsets, sizes, arr, None)
642    }
643
644    /// Build a single element [`LargeListViewArray`] and wrap as [`ScalarValue::LargeListView`]
645    pub fn build_large_list_view_scalar(self) -> ScalarValue {
646        ScalarValue::LargeListView(Arc::new(self.build_large_list_view_array()))
647    }
648
649    /// Helper function: convert this builder into a tuple of field and array
650    fn into_field_and_arr(self) -> (Arc<Field>, ArrayRef) {
651        let Self {
652            arr,
653            nullable,
654            field_name,
655            field_metadata,
656        } = self;
657        let data_type = arr.data_type().to_owned();
658        let field = match field_name {
659            Some(name) => Field::new(name, data_type, nullable),
660            None => Field::new_list_field(data_type, nullable),
661        };
662        (Arc::new(field.with_metadata(field_metadata)), arr)
663    }
664}
665
666/// Wrap arrays into a single element `ListArray`.
667///
668/// Example:
669/// ```
670/// use arrow::array::{Int32Array, ListArray, ArrayRef};
671/// use arrow::datatypes::{Int32Type, Field};
672/// use std::sync::Arc;
673///
674/// let arr1 = Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef;
675/// let arr2 = Arc::new(Int32Array::from(vec![4, 5, 6])) as ArrayRef;
676///
677/// let list_arr = datafusion_common::utils::arrays_into_list_array([arr1, arr2]).unwrap();
678///
679/// let expected = ListArray::from_iter_primitive::<Int32Type, _, _>(
680///    vec![
681///     Some(vec![Some(1), Some(2), Some(3)]),
682///     Some(vec![Some(4), Some(5), Some(6)]),
683///    ]
684/// );
685///
686/// assert_eq!(list_arr, expected);
687/// ```
688pub fn arrays_into_list_array(
689    arr: impl IntoIterator<Item = ArrayRef>,
690) -> Result<ListArray> {
691    let arr = arr.into_iter().collect::<Vec<_>>();
692    assert_or_internal_err!(!arr.is_empty(), "Cannot wrap empty array into list array");
693
694    let lens = arr.iter().map(|x| x.len()).collect::<Vec<_>>();
695    // Assume data type is consistent
696    let data_type = arr[0].data_type().to_owned();
697    let values = arr.iter().map(|x| x.as_ref()).collect::<Vec<_>>();
698    Ok(ListArray::new(
699        Arc::new(Field::new_list_field(data_type, true)),
700        OffsetBuffer::from_lengths(lens),
701        arrow::compute::concat(values.as_slice())?,
702        None,
703    ))
704}
705
706/// Helper function to convert a ListArray into a vector of ArrayRefs.
707pub fn list_to_arrays<O: OffsetSizeTrait>(a: &ArrayRef) -> Vec<ArrayRef> {
708    a.as_list::<O>().iter().flatten().collect::<Vec<_>>()
709}
710
711/// Helper function to convert a FixedSizeListArray into a vector of ArrayRefs.
712pub fn fixed_size_list_to_arrays(a: &ArrayRef) -> Vec<ArrayRef> {
713    a.as_fixed_size_list().iter().flatten().collect::<Vec<_>>()
714}
715
716/// Get the base type of a data type.
717///
718/// Example
719/// ```
720/// use arrow::datatypes::{DataType, Field};
721/// use datafusion_common::utils::base_type;
722/// use std::sync::Arc;
723///
724/// let data_type =
725///     DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
726/// assert_eq!(base_type(&data_type), DataType::Int32);
727///
728/// let data_type = DataType::Int32;
729/// assert_eq!(base_type(&data_type), DataType::Int32);
730/// ```
731pub fn base_type(data_type: &DataType) -> DataType {
732    match data_type {
733        DataType::List(field)
734        | DataType::LargeList(field)
735        | DataType::ListView(field)
736        | DataType::LargeListView(field)
737        | DataType::FixedSizeList(field, _) => base_type(field.data_type()),
738        _ => data_type.to_owned(),
739    }
740}
741
742// TODO: Modify this to also allow specifying how listviews should be treated.
743//       For example if cast to List (default) or maintain as ListView (requires
744//       function to implement support for ListViews)
745//       https://github.com/apache/datafusion/issues/21777
746/// Information about how to coerce lists.
747#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
748pub enum ListCoercion {
749    /// [`DataType::FixedSizeList`] should be coerced to [`DataType::List`].
750    FixedSizedListToList,
751}
752
753/// A helper function to coerce base type in List.
754///
755/// Example
756/// ```
757/// use arrow::datatypes::{DataType, Field};
758/// use datafusion_common::utils::coerced_type_with_base_type_only;
759/// use std::sync::Arc;
760///
761/// let data_type = DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
762/// let base_type = DataType::Float64;
763/// let coerced_type = coerced_type_with_base_type_only(&data_type, &base_type, None);
764/// assert_eq!(coerced_type, DataType::List(Arc::new(Field::new_list_field(DataType::Float64, true))));
765/// ```
766pub fn coerced_type_with_base_type_only(
767    data_type: &DataType,
768    base_type: &DataType,
769    array_coercion: Option<&ListCoercion>,
770) -> DataType {
771    match (data_type, array_coercion) {
772        (DataType::List(field), _)
773        | (DataType::FixedSizeList(field, _), Some(ListCoercion::FixedSizedListToList)) =>
774        {
775            let field_type = coerced_type_with_base_type_only(
776                field.data_type(),
777                base_type,
778                array_coercion,
779            );
780
781            DataType::List(Arc::new(Field::new(
782                field.name(),
783                field_type,
784                field.is_nullable(),
785            )))
786        }
787        (DataType::FixedSizeList(field, len), _) => {
788            let field_type = coerced_type_with_base_type_only(
789                field.data_type(),
790                base_type,
791                array_coercion,
792            );
793
794            DataType::FixedSizeList(
795                Arc::new(Field::new(field.name(), field_type, field.is_nullable())),
796                *len,
797            )
798        }
799        (DataType::ListView(field), _) => {
800            let field_type = coerced_type_with_base_type_only(
801                field.data_type(),
802                base_type,
803                array_coercion,
804            );
805
806            DataType::ListView(Arc::new(Field::new(
807                field.name(),
808                field_type,
809                field.is_nullable(),
810            )))
811        }
812        (DataType::LargeList(field), _) => {
813            let field_type = coerced_type_with_base_type_only(
814                field.data_type(),
815                base_type,
816                array_coercion,
817            );
818
819            DataType::LargeList(Arc::new(Field::new(
820                field.name(),
821                field_type,
822                field.is_nullable(),
823            )))
824        }
825        (DataType::LargeListView(field), _) => {
826            let field_type = coerced_type_with_base_type_only(
827                field.data_type(),
828                base_type,
829                array_coercion,
830            );
831
832            DataType::LargeListView(Arc::new(Field::new(
833                field.name(),
834                field_type,
835                field.is_nullable(),
836            )))
837        }
838
839        _ => base_type.clone(),
840    }
841}
842
843/// Recursively coerce and `FixedSizeList` elements to `List`
844pub fn coerced_fixed_size_list_to_list(data_type: &DataType) -> DataType {
845    match data_type {
846        DataType::List(field) | DataType::FixedSizeList(field, _) => {
847            let field_type = coerced_fixed_size_list_to_list(field.data_type());
848
849            DataType::List(Arc::new(Field::new(
850                field.name(),
851                field_type,
852                field.is_nullable(),
853            )))
854        }
855        DataType::ListView(field) => {
856            let field_type = coerced_fixed_size_list_to_list(field.data_type());
857
858            DataType::ListView(Arc::new(Field::new(
859                field.name(),
860                field_type,
861                field.is_nullable(),
862            )))
863        }
864        DataType::LargeList(field) => {
865            let field_type = coerced_fixed_size_list_to_list(field.data_type());
866
867            DataType::LargeList(Arc::new(Field::new(
868                field.name(),
869                field_type,
870                field.is_nullable(),
871            )))
872        }
873        DataType::LargeListView(field) => {
874            let field_type = coerced_fixed_size_list_to_list(field.data_type());
875
876            DataType::LargeListView(Arc::new(Field::new(
877                field.name(),
878                field_type,
879                field.is_nullable(),
880            )))
881        }
882
883        _ => data_type.clone(),
884    }
885}
886
887/// Compute the number of dimensions in a list data type.
888pub fn list_ndims(data_type: &DataType) -> u64 {
889    match data_type {
890        DataType::List(field)
891        | DataType::LargeList(field)
892        | DataType::ListView(field)
893        | DataType::LargeListView(field)
894        | DataType::FixedSizeList(field, _) => 1 + list_ndims(field.data_type()),
895        _ => 0,
896    }
897}
898
899/// Adopted from strsim-rs for string similarity metrics
900pub mod datafusion_strsim {
901    // Source: https://github.com/dguo/strsim-rs/blob/master/src/lib.rs
902    // License: https://github.com/dguo/strsim-rs/blob/master/LICENSE
903    use std::cmp::min;
904    use std::str::Chars;
905
906    struct StringWrapper<'a>(&'a str);
907
908    impl<'b> IntoIterator for &StringWrapper<'b> {
909        type Item = char;
910        type IntoIter = Chars<'b>;
911
912        fn into_iter(self) -> Self::IntoIter {
913            self.0.chars()
914        }
915    }
916
917    /// Calculates the minimum number of insertions, deletions, and substitutions
918    /// required to change one sequence into the other, using a reusable cache buffer.
919    ///
920    /// This is the generic implementation that works with any iterator types.
921    /// The `cache` buffer will be resized as needed and reused across calls.
922    fn generic_levenshtein_with_buffer<'a, 'b, Iter1, Iter2, Elem1, Elem2>(
923        a: &'a Iter1,
924        b: &'b Iter2,
925        cache: &mut Vec<usize>,
926    ) -> usize
927    where
928        &'a Iter1: IntoIterator<Item = Elem1>,
929        &'b Iter2: IntoIterator<Item = Elem2>,
930        Elem1: PartialEq<Elem2>,
931    {
932        let b_len = b.into_iter().count();
933
934        if a.into_iter().next().is_none() {
935            return b_len;
936        }
937
938        // Resize cache to fit b_len elements
939        cache.clear();
940        cache.extend(1..=b_len);
941
942        let mut result = 0;
943
944        for (i, a_elem) in a.into_iter().enumerate() {
945            result = i + 1;
946            let mut distance_b = i;
947
948            for (j, b_elem) in b.into_iter().enumerate() {
949                let cost = usize::from(a_elem != b_elem);
950                let distance_a = distance_b + cost;
951                distance_b = cache[j];
952                result = min(result + 1, min(distance_a, distance_b + 1));
953                cache[j] = result;
954            }
955        }
956
957        result
958    }
959
960    /// Calculates the minimum number of insertions, deletions, and substitutions
961    /// required to change one sequence into the other.
962    fn generic_levenshtein<'a, 'b, Iter1, Iter2, Elem1, Elem2>(
963        a: &'a Iter1,
964        b: &'b Iter2,
965    ) -> usize
966    where
967        &'a Iter1: IntoIterator<Item = Elem1>,
968        &'b Iter2: IntoIterator<Item = Elem2>,
969        Elem1: PartialEq<Elem2>,
970    {
971        let mut cache = Vec::new();
972        generic_levenshtein_with_buffer(a, b, &mut cache)
973    }
974
975    /// Calculates the minimum number of insertions, deletions, and substitutions
976    /// required to change one string into the other.
977    ///
978    /// ```
979    /// use datafusion_common::utils::datafusion_strsim::levenshtein;
980    ///
981    /// assert_eq!(3, levenshtein("kitten", "sitting"));
982    /// ```
983    pub fn levenshtein(a: &str, b: &str) -> usize {
984        generic_levenshtein(&StringWrapper(a), &StringWrapper(b))
985    }
986
987    /// Calculates the Levenshtein distance using a reusable cache buffer.
988    /// This avoids allocating a new Vec for each call, improving performance
989    /// when computing many distances.
990    ///
991    /// The `cache` buffer will be resized as needed and reused across calls.
992    pub fn levenshtein_with_buffer(a: &str, b: &str, cache: &mut Vec<usize>) -> usize {
993        generic_levenshtein_with_buffer(&StringWrapper(a), &StringWrapper(b), cache)
994    }
995
996    /// Calculates the normalized Levenshtein distance between two strings.
997    /// The normalized distance is a value between 0.0 and 1.0, where 1.0 indicates
998    /// that the strings are identical and 0.0 indicates no similarity.
999    ///
1000    /// ```
1001    /// use datafusion_common::utils::datafusion_strsim::normalized_levenshtein;
1002    ///
1003    /// assert!((normalized_levenshtein("kitten", "sitting") - 0.57142).abs() < 0.00001);
1004    ///
1005    /// assert!(normalized_levenshtein("", "second").abs() < 0.00001);
1006    ///
1007    /// assert!((normalized_levenshtein("kitten", "sitten") - 0.833).abs() < 0.001);
1008    /// ```
1009    pub fn normalized_levenshtein(a: &str, b: &str) -> f64 {
1010        if a.is_empty() && b.is_empty() {
1011            return 1.0;
1012        }
1013        1.0 - (levenshtein(a, b) as f64)
1014            / (a.chars().count().max(b.chars().count()) as f64)
1015    }
1016}
1017
1018/// Merges collections `first` and `second`, removes duplicates and sorts the
1019/// result, returning it as a [`Vec`].
1020pub fn merge_and_order_indices<T: Borrow<usize>, S: Borrow<usize>>(
1021    first: impl IntoIterator<Item = T>,
1022    second: impl IntoIterator<Item = S>,
1023) -> Vec<usize> {
1024    let mut result: Vec<_> = first
1025        .into_iter()
1026        .map(|e| *e.borrow())
1027        .chain(second.into_iter().map(|e| *e.borrow()))
1028        .collect::<HashSet<_>>()
1029        .into_iter()
1030        .collect();
1031    result.sort_unstable();
1032    result
1033}
1034
1035/// Calculates the set difference between sequences `first` and `second`,
1036/// returning the result as a [`Vec`]. Preserves the ordering of `first`.
1037pub fn set_difference<T: Borrow<usize>, S: Borrow<usize>>(
1038    first: impl IntoIterator<Item = T>,
1039    second: impl IntoIterator<Item = S>,
1040) -> Vec<usize> {
1041    let set: HashSet<_> = second.into_iter().map(|e| *e.borrow()).collect();
1042    first
1043        .into_iter()
1044        .map(|e| *e.borrow())
1045        .filter(|e| !set.contains(e))
1046        .collect()
1047}
1048
1049/// Find indices of each element in `targets` inside `items`. If one of the
1050/// elements is absent in `items`, returns an error.
1051pub fn find_indices<T: PartialEq, S: Borrow<T>>(
1052    items: &[T],
1053    targets: impl IntoIterator<Item = S>,
1054) -> Result<Vec<usize>> {
1055    targets
1056        .into_iter()
1057        .map(|target| items.iter().position(|e| target.borrow().eq(e)))
1058        .collect::<Option<_>>()
1059        .ok_or_else(|| _exec_datafusion_err!("Target not found"))
1060}
1061
1062/// Transposes the given vector of vectors.
1063pub fn transpose<T>(original: Vec<Vec<T>>) -> Vec<Vec<T>> {
1064    match original.as_slice() {
1065        [] => vec![],
1066        [first, ..] => {
1067            let mut result = (0..first.len())
1068                .map(|_| Vec::with_capacity(original.len()))
1069                .collect::<Vec<_>>();
1070            for row in original {
1071                for (item, transposed_row) in row.into_iter().zip(&mut result) {
1072                    transposed_row.push(item);
1073                }
1074            }
1075            result
1076        }
1077    }
1078}
1079
1080/// Computes the `skip` and `fetch` parameters of a single limit that would be
1081/// equivalent to two consecutive limits with the given `skip`/`fetch` parameters.
1082///
1083/// There are multiple cases to consider:
1084///
1085/// # Case 0: Parent and child are disjoint (`child_fetch <= skip`).
1086///
1087/// ```text
1088///   Before merging:
1089///                     |........skip........|---fetch-->|     Parent limit
1090///    |...child_skip...|---child_fetch-->|                    Child limit
1091/// ```
1092///
1093///   After merging:
1094/// ```text
1095///    |.........(child_skip + skip).........|
1096/// ```
1097///
1098/// # Case 1: Parent is beyond child's range (`skip < child_fetch <= skip + fetch`).
1099///
1100///   Before merging:
1101/// ```text
1102///                     |...skip...|------------fetch------------>|   Parent limit
1103///    |...child_skip...|-------------child_fetch------------>|       Child limit
1104/// ```
1105///
1106///   After merging:
1107/// ```text
1108///    |....(child_skip + skip)....|---(child_fetch - skip)-->|
1109/// ```
1110///
1111///  # Case 2: Parent is within child's range (`skip + fetch < child_fetch`).
1112///
1113///   Before merging:
1114/// ```text
1115///                     |...skip...|---fetch-->|                   Parent limit
1116///    |...child_skip...|-------------child_fetch------------>|    Child limit
1117/// ```
1118///
1119///   After merging:
1120/// ```text
1121///    |....(child_skip + skip)....|---fetch-->|
1122/// ```
1123pub fn combine_limit(
1124    parent_skip: usize,
1125    parent_fetch: Option<usize>,
1126    child_skip: usize,
1127    child_fetch: Option<usize>,
1128) -> (usize, Option<usize>) {
1129    let combined_skip = child_skip.saturating_add(parent_skip);
1130
1131    let combined_fetch = match (parent_fetch, child_fetch) {
1132        (Some(parent_fetch), Some(child_fetch)) => {
1133            Some(min(parent_fetch, child_fetch.saturating_sub(parent_skip)))
1134        }
1135        (Some(parent_fetch), None) => Some(parent_fetch),
1136        (None, Some(child_fetch)) => Some(child_fetch.saturating_sub(parent_skip)),
1137        (None, None) => None,
1138    };
1139
1140    (combined_skip, combined_fetch)
1141}
1142
1143/// Converts a wire integer to `usize`, rejecting out-of-range values.
1144/// `context` and `field` identify the value in the error message.
1145pub fn usize_from_wire<T>(value: T, context: &str, field: &str) -> Result<usize>
1146where
1147    T: TryInto<usize> + std::fmt::Display + Copy,
1148{
1149    value.try_into().map_err(|_| {
1150        _plan_datafusion_err!(
1151            "{context}: {field} wire value {value} is out of range for usize"
1152        )
1153    })
1154}
1155
1156/// Converts a `usize` to a wire integer, rejecting out-of-range values.
1157pub fn usize_to_wire<T: TryFrom<usize>>(
1158    value: usize,
1159    context: &str,
1160    field: &str,
1161) -> Result<T> {
1162    T::try_from(value).map_err(|_| {
1163        _plan_datafusion_err!(
1164            "{context}: {field} value {value} is out of range for the plan wire format"
1165        )
1166    })
1167}
1168
1169/// Returns the estimated number of threads available for parallel execution.
1170///
1171/// This is a wrapper around `std::thread::available_parallelism`, providing a default value
1172/// of `1` if the system's parallelism cannot be determined.
1173///
1174/// The result is cached after the first call.
1175pub fn get_available_parallelism() -> usize {
1176    static PARALLELISM: LazyLock<usize> = LazyLock::new(|| {
1177        available_parallelism()
1178            .unwrap_or(NonZero::new(1).expect("literal value `1` shouldn't be zero"))
1179            .get()
1180    });
1181    *PARALLELISM
1182}
1183
1184/// Converts a collection of function arguments into a fixed-size array of length N
1185/// producing a reasonable error message in case of unexpected number of arguments.
1186///
1187/// # Example
1188/// ```
1189/// # use datafusion_common::Result;
1190/// # use datafusion_common::utils::take_function_args;
1191/// # use datafusion_common::ScalarValue;
1192/// fn my_function(args: &[ScalarValue]) -> Result<()> {
1193///     // function expects 2 args, so create a 2-element array
1194///     let [arg1, arg2] = take_function_args("my_function", args)?;
1195///     // ... do stuff..
1196///     Ok(())
1197/// }
1198///
1199/// // Calling the function with 1 argument produces an error:
1200/// let args = vec![ScalarValue::Int32(Some(10))];
1201/// let err = my_function(&args).unwrap_err();
1202/// assert_eq!(
1203///     err.to_string(),
1204///     "Execution error: my_function function requires 2 arguments, got 1"
1205/// );
1206/// // Calling the function with 2 arguments works great
1207/// let args = vec![ScalarValue::Int32(Some(10)), ScalarValue::Int32(Some(20))];
1208/// my_function(&args).unwrap();
1209/// ```
1210pub fn take_function_args<const N: usize, T>(
1211    function_name: &str,
1212    args: impl IntoIterator<Item = T>,
1213) -> Result<[T; N]> {
1214    let args = args.into_iter().collect::<Vec<_>>();
1215    args.try_into().map_err(|v: Vec<T>| {
1216        _exec_datafusion_err!(
1217            "{} function requires {} {}, got {}",
1218            function_name,
1219            N,
1220            if N == 1 { "argument" } else { "arguments" },
1221            v.len()
1222        )
1223    })
1224}
1225
1226/// Returns the number of values covered by an offset buffer.
1227///
1228/// Slicing a variable-length array narrows its offsets but retains its entire
1229/// values buffer. Use this span to size output buffers: it counts child elements
1230/// for lists and bytes for strings/binary arrays, including values in null rows.
1231/// An empty array still has one offset and therefore a span of zero.
1232#[inline]
1233pub fn offset_span_len<O: ArrowNativeType>(offsets: &OffsetBuffer<O>) -> usize {
1234    offset_span(offsets).1
1235}
1236
1237/// Returns the start and length of the values covered by an offset buffer.
1238///
1239/// The returned pair can be passed to [`Array::slice`] to select the visible
1240/// child values of a sliced list or map. For strings/binary arrays, the start
1241/// and length are measured in bytes. Values in null rows are included.
1242/// An empty array has a length of zero but may have a nonzero start.
1243///
1244/// ```
1245/// # use arrow::buffer::OffsetBuffer;
1246/// # use datafusion_common::utils::offset_span;
1247/// let offsets = OffsetBuffer::new(vec![100_i32, 103, 108].into());
1248/// assert_eq!(offset_span(&offsets), (100, 8));
1249/// ```
1250#[inline]
1251pub fn offset_span<O: ArrowNativeType>(offsets: &OffsetBuffer<O>) -> (usize, usize) {
1252    let start = offsets.first().as_usize();
1253    (start, offsets.last().as_usize() - start)
1254}
1255
1256/// Returns the inner values of a list, or an error otherwise
1257/// For [`ListArray`] and [`LargeListArray`], if it's sliced, it returns a
1258/// sliced array too. Therefore, too reconstruct a list using it,
1259/// you must adjust the offsets using [`adjust_offsets_for_slice`]
1260pub fn list_values(array: &dyn Array) -> Result<ArrayRef> {
1261    match array.data_type() {
1262        DataType::List(_) => Ok(sliced_list_values(array.as_list::<i32>())),
1263        DataType::LargeList(_) => Ok(sliced_list_values(array.as_list::<i64>())),
1264        DataType::FixedSizeList(_, _) => {
1265            Ok(Arc::clone(array.as_fixed_size_list().values()))
1266        }
1267        other => _exec_err!("expected list, got {other}"),
1268    }
1269}
1270
1271fn sliced_list_values<O: OffsetSizeTrait>(list: &GenericListArray<O>) -> ArrayRef {
1272    let values = list.values();
1273    let (start, len) = offset_span(list.offsets());
1274
1275    if start != 0 || len != values.len() {
1276        return values.slice(start, len);
1277    }
1278
1279    Arc::clone(values)
1280}
1281
1282/// If `list` is sliced, returns an adjusted offset buffer so that
1283/// it points to the sliced portion of the list values, and not the whole list values
1284pub fn adjust_offsets_for_slice<O: OffsetSizeTrait>(
1285    list: &GenericListArray<O>,
1286) -> OffsetBuffer<O> {
1287    let offsets = list.offsets();
1288
1289    offsets.clone().subtract(offsets[0])
1290}
1291
1292/// For lists and large lists, truncates the sublist of null values
1293/// Otherwise returns an error
1294pub fn remove_list_null_values(array: &ArrayRef) -> Result<ArrayRef> {
1295    // todo: handle list view and map
1296    match array.data_type() {
1297        DataType::List(_) => Ok(Arc::new(truncate_list_nulls(array.as_list::<i32>())?)),
1298        DataType::LargeList(_) => {
1299            Ok(Arc::new(truncate_list_nulls(array.as_list::<i64>())?))
1300        }
1301        dt => _exec_err!("expected List or LargeList, got {dt}"),
1302    }
1303}
1304
1305/// Create a new list array where all the nulls point to empty lists
1306fn truncate_list_nulls<O: OffsetSizeTrait>(
1307    list: &GenericListArray<O>,
1308) -> Result<GenericListArray<O>> {
1309    if let Some(nulls) = list.nulls()
1310        && nulls.null_count() > 0
1311    {
1312        let lengths = length(list)?;
1313        let zero: &dyn Datum = if lengths.data_type() == &DataType::Int32 {
1314            &Int32Array::new_scalar(0)
1315        } else {
1316            &Int64Array::new_scalar(0)
1317        };
1318
1319        let (mut valid_or_empty, _nulls) = eq(&lengths, zero)?.into_parts();
1320        valid_or_empty |= nulls.inner();
1321        let valid_or_empty = BooleanArray::from(valid_or_empty);
1322
1323        if valid_or_empty.has_false() {
1324            let array_data = list.values().to_data();
1325            let offsets = list.offsets();
1326            let capacity = offset_span_len(offsets);
1327            let mut mutable_array_data =
1328                MutableArrayData::new(vec![&array_data], false, capacity);
1329
1330            let (valid_or_empty, _nulls) = valid_or_empty.into_parts();
1331
1332            for (start, end) in valid_or_empty.set_slices() {
1333                mutable_array_data.try_extend(
1334                    0,
1335                    offsets[start].as_usize(),
1336                    offsets[end].as_usize(),
1337                )?;
1338            }
1339
1340            let lengths = std::iter::zip(offsets.lengths(), nulls)
1341                .map(|(length, is_valid)| if is_valid { length } else { 0 });
1342
1343            let offsets = OffsetBuffer::from_lengths(lengths);
1344            let values = make_array(mutable_array_data.freeze());
1345
1346            return Ok(GenericListArray::try_new(
1347                Arc::clone(list.value_field()),
1348                offsets,
1349                values,
1350                list.nulls().cloned(),
1351            )?);
1352        }
1353    }
1354    Ok(list.clone())
1355}
1356
1357/// If `array` is a list or a map, returns a new array of the same length as it's inner values
1358/// where each value is the 1-based index of the sublist it's contained. Example:
1359///
1360/// `[[1], [2, 3], [4, 5, 6]] =>  [1, 2, 2, 3, 3, 3]`
1361///
1362/// Otherwise returns an error
1363pub fn list_values_row_number(array: &dyn Array) -> Result<ArrayRef> {
1364    match array.data_type() {
1365        DataType::List(_) => Ok(Arc::new(variable_size_list_values_row_number::<
1366            Int32Type,
1367        >(array.as_list().offsets()))),
1368        DataType::LargeList(_) => Ok(Arc::new(variable_size_list_values_row_number::<
1369            Int64Type,
1370        >(array.as_list().offsets()))),
1371        DataType::ListView(_) => Ok(Arc::new(variable_size_list_values_row_number::<
1372            Int32Type,
1373        >(array.as_list_view().offsets()))),
1374        DataType::LargeListView(_) => {
1375            Ok(Arc::new(variable_size_list_values_row_number::<Int64Type>(
1376                array.as_list_view().offsets(),
1377            )))
1378        }
1379        DataType::FixedSizeList(_, _) => {
1380            let fixed_size_list = array.as_fixed_size_list();
1381
1382            Ok(Arc::new(fsl_values_row_number(
1383                fixed_size_list.value_length(),
1384                fixed_size_list.len(),
1385            )?))
1386        }
1387        DataType::Map(_, _) => Ok(Arc::new(variable_size_list_values_row_number::<
1388            Int32Type,
1389        >(array.as_map().offsets()))),
1390        other => _exec_err!("expected list, got {other}"),
1391    }
1392}
1393
1394/// [0, 2, 2, 5, 6] -> [0, 0, 2, 2, 2, 3]
1395fn variable_size_list_values_row_number<T: ArrowPrimitiveType>(
1396    offsets: &[T::Native],
1397) -> PrimitiveArray<T> {
1398    let mut rows_number = Vec::with_capacity(
1399        offsets[offsets.len() - 1].to_usize().unwrap() - offsets[0].to_usize().unwrap(),
1400    );
1401
1402    for (i, w) in offsets.windows(2).enumerate() {
1403        let len = w[1].as_usize() - w[0].as_usize();
1404        rows_number.extend(repeat_n(T::Native::usize_as(i), len));
1405    }
1406
1407    PrimitiveArray::new(rows_number.into(), None)
1408}
1409
1410/// (2, 3) -> [0, 0, 1, 1, 2, 2]
1411fn fsl_values_row_number(list_size: i32, array_len: usize) -> Result<Int32Array> {
1412    let list_size = list_size.to_usize().ok_or_else(|| {
1413        _exec_datafusion_err!("fsl_values_index: invalid list_size {list_size}")
1414    })?;
1415
1416    let mut rows_number = Vec::with_capacity(list_size * array_len);
1417
1418    for i in 0..array_len {
1419        rows_number.extend(repeat_n(i as i32, list_size));
1420    }
1421
1422    Ok(PrimitiveArray::new(rows_number.into(), None))
1423}
1424
1425/// Replace `-0.0` with `+0.0` in any `Float16`, `Float32`, or `Float64` array.
1426#[deprecated(
1427    since = "56.0.0",
1428    note = "use `datafusion_common::float_semantics::normalize_floats` instead"
1429)]
1430pub fn normalize_float_zero(array: &ArrayRef) -> ArrayRef {
1431    crate::float_semantics::normalize_floats(array)
1432}
1433
1434pub use crate::float_semantics::has_float_leaf;
1435
1436/// Replace `-0.0` with `+0.0` in `Float16`, `Float32`, or `Float64` scalar
1437/// values.
1438#[deprecated(since = "56.0.0", note = "use `ScalarValue::normalize` instead")]
1439pub fn normalize_float_zero_scalar(scalar: ScalarValue) -> ScalarValue {
1440    scalar.normalize()
1441}
1442
1443/// Apply a struct's nulls to one of its fields.
1444///
1445/// Arrays with validity bitmaps share their value buffers; unions and
1446/// run-end encoded arrays are rebuilt.
1447pub fn apply_parent_nulls(
1448    col: &ArrayRef,
1449    parent_nulls: Option<&NullBuffer>,
1450) -> Result<ArrayRef> {
1451    let Some(parent_nulls) = parent_nulls else {
1452        // If there are no parent nulls to apply, we can just return
1453        return Ok(Arc::clone(col));
1454    };
1455
1456    // NullArray is already entirely null and cannot have a validity bitmap.
1457    // If we have 0 parent nulls, we can also avoid extra work.
1458    if col.data_type().is_null() || parent_nulls.null_count() == 0 {
1459        return Ok(Arc::clone(col));
1460    }
1461
1462    if layout(col.data_type()).can_contain_null_mask {
1463        // `nullif` marks a row null where the mask is true and keeps the
1464        // field's own nulls. Only the validity bitmap is rebuilt; the value
1465        // buffers and child arrays are shared with `col`.
1466        let null_parents = BooleanArray::new(!parent_nulls.inner(), None);
1467        return Ok(nullif(col.as_ref(), &null_parents)?);
1468    }
1469
1470    // Unions and run-end encoded arrays have no validity bitmap of their own
1471    // and represent nulls in their children. Rebuild the array so null parents
1472    // become null values in those children.
1473    let data = col.to_data();
1474    let mut mutable = MutableArrayData::new(vec![&data], true, data.len());
1475    let mut end = 0;
1476    for (start, valid_end) in parent_nulls.valid_slices() {
1477        mutable.try_extend_nulls(start - end)?;
1478        mutable.try_extend(0, start, valid_end)?;
1479        end = valid_end;
1480    }
1481    mutable.try_extend_nulls(data.len() - end)?;
1482
1483    Ok(make_array(mutable.freeze()))
1484}
1485
1486#[cfg(test)]
1487mod tests {
1488    use std::collections::HashMap;
1489    use std::sync::Arc;
1490
1491    use super::*;
1492    use crate::ScalarValue::Null;
1493    use arrow::{
1494        array::{Float64Array, Int32Array, NullArray},
1495        datatypes::Int32Type,
1496    };
1497    #[cfg(feature = "sql")]
1498    use sqlparser::ast::Ident;
1499
1500    #[test]
1501    fn test_list_scalar_cast_preserves_target_element_metadata() -> Result<()> {
1502        let input =
1503            ListArray::from_iter_primitive::<Int32Type, _, _>(vec![Some(vec![Some(1)])]);
1504        let item = Field::new("item", DataType::Int32, true)
1505            .with_metadata(HashMap::from([("PARQUET:field_id".into(), "2".into())]));
1506        let target = DataType::List(Arc::new(item));
1507
1508        let casted = ScalarValue::List(Arc::new(input)).cast_to(&target)?;
1509        assert_eq!(casted.data_type(), target);
1510        assert_eq!(casted.to_array_of_size(2)?.data_type(), &target);
1511        Ok(())
1512    }
1513
1514    #[test]
1515    fn test_apply_parent_nulls_sliced() -> Result<()> {
1516        let child = Arc::new(
1517            Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5)]).slice(1, 3),
1518        ) as ArrayRef;
1519        let parent_nulls =
1520            NullBuffer::from(vec![true, true, true, false, true]).slice(1, 3);
1521        let result = apply_parent_nulls(&child, Some(&parent_nulls))?;
1522        assert_eq!(
1523            result.as_ref(),
1524            &Int32Array::from(vec![None, Some(3), None])
1525        );
1526        assert!(result.to_data().buffers()[0].ptr_eq(&child.to_data().buffers()[0]));
1527        Ok(())
1528    }
1529
1530    #[test]
1531    fn test_apply_parent_nulls_noop() -> Result<()> {
1532        let child = Arc::new(Int32Array::from(vec![Some(1), None, Some(3)])) as ArrayRef;
1533        for parent_nulls in [None, Some(NullBuffer::new_valid(3))] {
1534            assert!(Arc::ptr_eq(
1535                &apply_parent_nulls(&child, parent_nulls.as_ref())?,
1536                &child,
1537            ));
1538        }
1539        let child = Arc::new(NullArray::new(3)) as ArrayRef;
1540        assert!(Arc::ptr_eq(
1541            &apply_parent_nulls(&child, Some(&NullBuffer::new_null(3)))?,
1542            &child,
1543        ));
1544        let empty = child.slice(0, 0);
1545        assert!(Arc::ptr_eq(
1546            &apply_parent_nulls(&empty, Some(&NullBuffer::new_valid(0)))?,
1547            &empty,
1548        ));
1549        Ok(())
1550    }
1551
1552    #[test]
1553    fn test_offset_span() {
1554        let offsets = OffsetBuffer::new(vec![0_i32, 5, 8, 8, 12].into());
1555        assert_eq!(offset_span(&offsets), (0, 12));
1556        assert_eq!(offset_span(&offsets.slice(1, 2)), (5, 3));
1557        assert_eq!(offset_span_len(&offsets.slice(1, 2)), 3);
1558        assert_eq!(offset_span(&offsets.slice(2, 1)), (8, 0));
1559        assert_eq!(offset_span(&offsets.slice(4, 0)), (12, 0));
1560        assert_eq!(offset_span(&OffsetBuffer::<i64>::new_empty()), (0, 0));
1561        let large = OffsetBuffer::new(vec![i64::MAX - 10, i64::MAX].into());
1562        assert_eq!(offset_span(&large), ((i64::MAX - 10) as usize, 10));
1563    }
1564
1565    #[test]
1566    fn test_usize_wire_conversions() {
1567        assert_eq!(usize_from_wire(42_u64, "SomeExec", "fetch").unwrap(), 42);
1568        let err = usize_from_wire(-1_i64, "SomeExec", "skip").unwrap_err();
1569        assert_eq!(
1570            err.strip_backtrace(),
1571            "Error during planning: SomeExec: skip wire value -1 is out of range for usize"
1572        );
1573
1574        assert_eq!(usize_to_wire::<u32>(42, "SomeExec", "fetch").unwrap(), 42);
1575        let err = usize_to_wire::<u8>(256, "SomeExec", "fetch").unwrap_err();
1576        assert_eq!(
1577            err.strip_backtrace(),
1578            "Error during planning: SomeExec: fetch value 256 is out of range for the plan wire format"
1579        );
1580
1581        let max = usize_from_wire(u64::MAX, "SomeExec", "fetch");
1582        if usize::BITS >= u64::BITS {
1583            assert_eq!(max.unwrap(), usize::MAX);
1584        } else {
1585            assert!(max.is_err());
1586        }
1587    }
1588
1589    #[test]
1590    fn test_bisect_linear_left_and_right() -> Result<()> {
1591        let arrays: Vec<ArrayRef> = vec![
1592            Arc::new(Float64Array::from(vec![5.0, 7.0, 8.0, 9., 10.])),
1593            Arc::new(Float64Array::from(vec![2.0, 3.0, 3.0, 4.0, 5.0])),
1594            Arc::new(Float64Array::from(vec![5.0, 7.0, 8.0, 10., 11.0])),
1595            Arc::new(Float64Array::from(vec![15.0, 13.0, 8.0, 5., 0.0])),
1596        ];
1597        let search_tuple: Vec<ScalarValue> = vec![
1598            ScalarValue::Float64(Some(8.0)),
1599            ScalarValue::Float64(Some(3.0)),
1600            ScalarValue::Float64(Some(8.0)),
1601            ScalarValue::Float64(Some(8.0)),
1602        ];
1603        let ords = [
1604            SortOptions {
1605                descending: false,
1606                nulls_first: true,
1607            },
1608            SortOptions {
1609                descending: false,
1610                nulls_first: true,
1611            },
1612            SortOptions {
1613                descending: false,
1614                nulls_first: true,
1615            },
1616            SortOptions {
1617                descending: true,
1618                nulls_first: true,
1619            },
1620        ];
1621        let res = bisect::<true>(&arrays, &search_tuple, &ords)?;
1622        assert_eq!(res, 2);
1623        let res = bisect::<false>(&arrays, &search_tuple, &ords)?;
1624        assert_eq!(res, 3);
1625        let res = linear_search::<true>(&arrays, &search_tuple, &ords)?;
1626        assert_eq!(res, 2);
1627        let res = linear_search::<false>(&arrays, &search_tuple, &ords)?;
1628        assert_eq!(res, 3);
1629        Ok(())
1630    }
1631
1632    #[test]
1633    fn vector_ord() {
1634        assert!(vec![1, 0, 0, 0, 0, 0, 0, 1] < vec![1, 0, 0, 0, 0, 0, 0, 2]);
1635        assert!(vec![1, 0, 0, 0, 0, 0, 1, 1] > vec![1, 0, 0, 0, 0, 0, 0, 2]);
1636        assert!(
1637            vec![
1638                ScalarValue::Int32(Some(2)),
1639                Null,
1640                ScalarValue::Int32(Some(0)),
1641            ] < vec![
1642                ScalarValue::Int32(Some(2)),
1643                Null,
1644                ScalarValue::Int32(Some(1)),
1645            ]
1646        );
1647        assert!(
1648            vec![
1649                ScalarValue::Int32(Some(2)),
1650                ScalarValue::Int32(None),
1651                ScalarValue::Int32(Some(0)),
1652            ] < vec![
1653                ScalarValue::Int32(Some(2)),
1654                ScalarValue::Int32(None),
1655                ScalarValue::Int32(Some(1)),
1656            ]
1657        );
1658    }
1659
1660    #[test]
1661    fn ord_same_type() {
1662        assert!((ScalarValue::Int32(Some(2)) < ScalarValue::Int32(Some(3))));
1663    }
1664
1665    #[test]
1666    fn test_bisect_linear_left_and_right_diff_sort() -> Result<()> {
1667        // Descending, left
1668        let arrays: Vec<ArrayRef> =
1669            vec![Arc::new(Float64Array::from(vec![4.0, 3.0, 2.0, 1.0, 0.0]))];
1670        let search_tuple: Vec<ScalarValue> = vec![ScalarValue::Float64(Some(4.0))];
1671        let ords = [SortOptions {
1672            descending: true,
1673            nulls_first: true,
1674        }];
1675        let res = bisect::<true>(&arrays, &search_tuple, &ords)?;
1676        assert_eq!(res, 0);
1677        let res = linear_search::<true>(&arrays, &search_tuple, &ords)?;
1678        assert_eq!(res, 0);
1679
1680        // Descending, right
1681        let arrays: Vec<ArrayRef> =
1682            vec![Arc::new(Float64Array::from(vec![4.0, 3.0, 2.0, 1.0, 0.0]))];
1683        let search_tuple: Vec<ScalarValue> = vec![ScalarValue::Float64(Some(4.0))];
1684        let ords = [SortOptions {
1685            descending: true,
1686            nulls_first: true,
1687        }];
1688        let res = bisect::<false>(&arrays, &search_tuple, &ords)?;
1689        assert_eq!(res, 1);
1690        let res = linear_search::<false>(&arrays, &search_tuple, &ords)?;
1691        assert_eq!(res, 1);
1692
1693        // Ascending, left
1694        let arrays: Vec<ArrayRef> =
1695            vec![Arc::new(Float64Array::from(vec![5.0, 7.0, 8.0, 9., 10.]))];
1696        let search_tuple: Vec<ScalarValue> = vec![ScalarValue::Float64(Some(7.0))];
1697        let ords = [SortOptions {
1698            descending: false,
1699            nulls_first: true,
1700        }];
1701        let res = bisect::<true>(&arrays, &search_tuple, &ords)?;
1702        assert_eq!(res, 1);
1703        let res = linear_search::<true>(&arrays, &search_tuple, &ords)?;
1704        assert_eq!(res, 1);
1705
1706        // Ascending, right
1707        let arrays: Vec<ArrayRef> =
1708            vec![Arc::new(Float64Array::from(vec![5.0, 7.0, 8.0, 9., 10.]))];
1709        let search_tuple: Vec<ScalarValue> = vec![ScalarValue::Float64(Some(7.0))];
1710        let ords = [SortOptions {
1711            descending: false,
1712            nulls_first: true,
1713        }];
1714        let res = bisect::<false>(&arrays, &search_tuple, &ords)?;
1715        assert_eq!(res, 2);
1716        let res = linear_search::<false>(&arrays, &search_tuple, &ords)?;
1717        assert_eq!(res, 2);
1718
1719        let arrays: Vec<ArrayRef> = vec![
1720            Arc::new(Float64Array::from(vec![5.0, 7.0, 8.0, 8.0, 9., 10.])),
1721            Arc::new(Float64Array::from(vec![10.0, 9.0, 8.0, 7.5, 7., 6.])),
1722        ];
1723        let search_tuple: Vec<ScalarValue> = vec![
1724            ScalarValue::Float64(Some(8.0)),
1725            ScalarValue::Float64(Some(8.0)),
1726        ];
1727        let ords = [
1728            SortOptions {
1729                descending: false,
1730                nulls_first: true,
1731            },
1732            SortOptions {
1733                descending: true,
1734                nulls_first: true,
1735            },
1736        ];
1737        let res = bisect::<false>(&arrays, &search_tuple, &ords)?;
1738        assert_eq!(res, 3);
1739        let res = linear_search::<false>(&arrays, &search_tuple, &ords)?;
1740        assert_eq!(res, 3);
1741
1742        let res = bisect::<true>(&arrays, &search_tuple, &ords)?;
1743        assert_eq!(res, 2);
1744        let res = linear_search::<true>(&arrays, &search_tuple, &ords)?;
1745        assert_eq!(res, 2);
1746        Ok(())
1747    }
1748
1749    #[test]
1750    fn test_evaluate_partition_ranges() -> Result<()> {
1751        let arrays: Vec<ArrayRef> = vec![
1752            Arc::new(Float64Array::from(vec![1.0, 1.0, 1.0, 2.0, 2.0, 2.0])),
1753            Arc::new(Float64Array::from(vec![4.0, 4.0, 3.0, 2.0, 1.0, 1.0])),
1754        ];
1755        let n_row = arrays[0].len();
1756        let options: Vec<SortOptions> = vec![
1757            SortOptions {
1758                descending: false,
1759                nulls_first: false,
1760            },
1761            SortOptions {
1762                descending: true,
1763                nulls_first: false,
1764            },
1765        ];
1766        let sort_columns = arrays
1767            .into_iter()
1768            .zip(options)
1769            .map(|(values, options)| SortColumn {
1770                values,
1771                options: Some(options),
1772            })
1773            .collect::<Vec<_>>();
1774        let ranges = evaluate_partition_ranges(n_row, &sort_columns)?;
1775        assert_eq!(ranges.len(), 4);
1776        assert_eq!(ranges[0], Range { start: 0, end: 2 });
1777        assert_eq!(ranges[1], Range { start: 2, end: 3 });
1778        assert_eq!(ranges[2], Range { start: 3, end: 4 });
1779        assert_eq!(ranges[3], Range { start: 4, end: 6 });
1780        Ok(())
1781    }
1782
1783    #[cfg(feature = "sql")]
1784    #[test]
1785    fn test_quote_identifier() -> Result<()> {
1786        let cases = vec![
1787            ("foo", r#"foo"#),
1788            ("_foo", r#"_foo"#),
1789            ("foo_bar", r#"foo_bar"#),
1790            ("foo-bar", r#""foo-bar""#),
1791            // name itself has a period, needs to be quoted
1792            ("foo.bar", r#""foo.bar""#),
1793            ("Foo", r#""Foo""#),
1794            ("Foo.Bar", r#""Foo.Bar""#),
1795            // name starting with a number needs to be quoted
1796            ("test1", r#"test1"#),
1797            ("1test", r#""1test""#),
1798        ];
1799
1800        for (identifier, quoted_identifier) in cases {
1801            println!("input: \n{identifier}\nquoted_identifier:\n{quoted_identifier}");
1802
1803            assert_eq!(quote_identifier(identifier), quoted_identifier);
1804
1805            // When parsing the quoted identifier, it should be a
1806            // a single identifier without normalization, and not in multiple parts
1807            let quote_style = if quoted_identifier.starts_with('"') {
1808                Some('"')
1809            } else {
1810                None
1811            };
1812
1813            let expected_parsed = vec![Ident {
1814                value: identifier.to_string(),
1815                quote_style,
1816                span: sqlparser::tokenizer::Span::empty(),
1817            }];
1818
1819            assert_eq!(
1820                parse_identifiers(quoted_identifier).unwrap(),
1821                expected_parsed
1822            );
1823        }
1824
1825        Ok(())
1826    }
1827
1828    #[test]
1829    fn test_get_at_indices() -> Result<()> {
1830        let in_vec = vec![1, 2, 3, 4, 5, 6, 7];
1831        assert_eq!(get_at_indices(&in_vec, [0, 2])?, vec![1, 3]);
1832        assert_eq!(get_at_indices(&in_vec, [4, 2])?, vec![5, 3]);
1833        // 7 is outside the range
1834        assert!(get_at_indices(&in_vec, [7]).is_err());
1835        Ok(())
1836    }
1837
1838    #[test]
1839    fn test_longest_consecutive_prefix() {
1840        assert_eq!(longest_consecutive_prefix([0, 3, 4]), 1);
1841        assert_eq!(longest_consecutive_prefix([0, 1, 3, 4]), 2);
1842        assert_eq!(longest_consecutive_prefix([0, 1, 2, 3, 4]), 5);
1843        assert_eq!(longest_consecutive_prefix([1, 2, 3, 4]), 0);
1844    }
1845
1846    #[test]
1847    fn test_merge_and_order_indices() {
1848        assert_eq!(
1849            merge_and_order_indices([0, 3, 4], [1, 3, 5]),
1850            vec![0, 1, 3, 4, 5]
1851        );
1852        // Result should be ordered, even if inputs are not
1853        assert_eq!(
1854            merge_and_order_indices([3, 0, 4], [5, 1, 3]),
1855            vec![0, 1, 3, 4, 5]
1856        );
1857    }
1858
1859    #[test]
1860    fn test_set_difference() {
1861        assert_eq!(set_difference([0, 3, 4], [1, 2]), vec![0, 3, 4]);
1862        assert_eq!(set_difference([0, 3, 4], [1, 2, 4]), vec![0, 3]);
1863        // return value should have same ordering with the in1
1864        assert_eq!(set_difference([3, 4, 0], [1, 2, 4]), vec![3, 0]);
1865        assert_eq!(set_difference([0, 3, 4], [4, 1, 2]), vec![0, 3]);
1866        assert_eq!(set_difference([3, 4, 0], [4, 1, 2]), vec![3, 0]);
1867    }
1868
1869    #[test]
1870    fn test_find_indices() -> Result<()> {
1871        assert_eq!(find_indices(&[0, 3, 4], [0, 3, 4])?, vec![0, 1, 2]);
1872        assert_eq!(find_indices(&[0, 3, 4], [0, 4, 3])?, vec![0, 2, 1]);
1873        assert_eq!(find_indices(&[3, 0, 4], [0, 3])?, vec![1, 0]);
1874        assert!(find_indices(&[0, 3], [0, 3, 4]).is_err());
1875        assert!(find_indices(&[0, 3, 4], [0, 2]).is_err());
1876        Ok(())
1877    }
1878
1879    #[test]
1880    fn test_transpose() -> Result<()> {
1881        let in_data = vec![vec![1, 2, 3], vec![4, 5, 6]];
1882        let transposed = transpose(in_data);
1883        let expected = vec![vec![1, 4], vec![2, 5], vec![3, 6]];
1884        assert_eq!(expected, transposed);
1885        Ok(())
1886    }
1887
1888    #[test]
1889    fn test_sliced_list_values() {
1890        let data = vec![
1891            Some(vec![Some(0), Some(1), Some(2)]),
1892            None,
1893            Some(vec![Some(3), None, Some(5)]),
1894            Some(vec![Some(6), Some(7)]),
1895        ];
1896
1897        let list = ListArray::from_iter_primitive::<Int32Type, _, _>(data);
1898
1899        assert_eq!(
1900            sliced_list_values(&list).as_primitive(),
1901            &Int32Array::from(vec![
1902                Some(0),
1903                Some(1),
1904                Some(2),
1905                Some(3),
1906                None,
1907                Some(5),
1908                Some(6),
1909                Some(7)
1910            ])
1911        );
1912
1913        assert_eq!(
1914            sliced_list_values(&list.slice(0, 1)).as_primitive(),
1915            &Int32Array::from(vec![Some(0), Some(1), Some(2)])
1916        );
1917
1918        assert_eq!(
1919            sliced_list_values(&list.slice(2, 1)).as_primitive(),
1920            &Int32Array::from(vec![Some(3), None, Some(5)])
1921        );
1922
1923        assert_eq!(
1924            sliced_list_values(&list.slice(3, 1)).as_primitive(),
1925            &Int32Array::from(vec![Some(6), Some(7)])
1926        );
1927
1928        assert!(sliced_list_values(&list.slice(0, 0)).is_empty());
1929        assert!(sliced_list_values(&list.slice(1, 0)).is_empty());
1930        assert!(sliced_list_values(&list.slice(3, 0)).is_empty());
1931    }
1932
1933    #[test]
1934    fn test_adjust_offsets() {
1935        let data = vec![
1936            Some(vec![Some(0), Some(1), Some(2)]),
1937            None,
1938            Some(vec![Some(3), None, Some(5)]),
1939            Some(vec![Some(6), Some(7)]),
1940        ];
1941        let list = ListArray::from_iter_primitive::<Int32Type, _, _>(data);
1942
1943        assert_eq!(
1944            adjust_offsets_for_slice(&list),
1945            OffsetBuffer::from_lengths([3, 0, 3, 2])
1946        );
1947
1948        assert_eq!(
1949            adjust_offsets_for_slice(&list.slice(0, 1)),
1950            OffsetBuffer::from_lengths([3])
1951        );
1952
1953        assert_eq!(
1954            adjust_offsets_for_slice(&list.slice(1, 2)),
1955            OffsetBuffer::from_lengths([0, 3])
1956        );
1957
1958        assert_eq!(
1959            adjust_offsets_for_slice(&list.slice(1, 3)),
1960            OffsetBuffer::from_lengths([0, 3, 2])
1961        );
1962
1963        assert_eq!(
1964            adjust_offsets_for_slice(&list.slice(0, 0)),
1965            OffsetBuffer::from_lengths([])
1966        );
1967
1968        assert_eq!(
1969            adjust_offsets_for_slice(&list.slice(1, 0)),
1970            OffsetBuffer::from_lengths([])
1971        );
1972
1973        assert_eq!(
1974            adjust_offsets_for_slice(&list.slice(3, 0)),
1975            OffsetBuffer::from_lengths([])
1976        );
1977    }
1978
1979    fn create_i32_list(
1980        values: impl Into<Int32Array>,
1981        offsets: OffsetBuffer<i32>,
1982        nulls: Option<NullBuffer>,
1983    ) -> ListArray {
1984        let list_field = Arc::new(Field::new_list_field(DataType::Int32, true));
1985
1986        ListArray::new(list_field, offsets, Arc::new(values.into()), nulls)
1987    }
1988
1989    #[test]
1990    fn test_remove_list_null_values_list() {
1991        let list = Arc::new(create_i32_list(
1992            vec![100, 20, 10, 0, 0, 0, 0, 1, 50],
1993            OffsetBuffer::<i32>::from_lengths(vec![3, 4, 0, 2, 0]),
1994            Some(NullBuffer::from(vec![true, false, false, true, false])),
1995        )) as ArrayRef;
1996
1997        let res = remove_list_null_values(&list).unwrap();
1998        let res = res.as_list::<i32>();
1999
2000        let expected = Arc::new(create_i32_list(
2001            vec![100, 20, 10, 1, 50],
2002            OffsetBuffer::<i32>::from_lengths(vec![3, 0, 0, 2, 0]),
2003            Some(NullBuffer::from(vec![true, false, false, true, false])),
2004        )) as ArrayRef;
2005        let expected = expected.as_list::<i32>();
2006
2007        assert_eq!(res, expected);
2008        // check above skips inner value of nulls
2009        assert_eq!(res.values(), expected.values());
2010        assert_eq!(res.offsets(), expected.offsets());
2011    }
2012
2013    #[test]
2014    fn test_list_array_values_row_number() {
2015        assert_eq!(
2016            variable_size_list_values_row_number::<Int32Type>(
2017                &OffsetBuffer::from_lengths([1, 3, 0, 2,])
2018            ),
2019            Int32Array::from(vec![0, 1, 1, 1, 3, 3])
2020        );
2021
2022        assert_eq!(
2023            variable_size_list_values_row_number::<Int32Type>(
2024                &OffsetBuffer::from_lengths([])
2025            ),
2026            Int32Array::new_null(0)
2027        );
2028
2029        assert_eq!(
2030            variable_size_list_values_row_number::<Int32Type>(
2031                &OffsetBuffer::from_lengths([0])
2032            ),
2033            Int32Array::new_null(0)
2034        );
2035
2036        assert_eq!(
2037            variable_size_list_values_row_number::<Int32Type>(
2038                &OffsetBuffer::from_lengths([0, 0])
2039            ),
2040            Int32Array::new_null(0)
2041        );
2042
2043        assert_eq!(
2044            variable_size_list_values_row_number::<Int32Type>(
2045                &OffsetBuffer::from_lengths([1])
2046            ),
2047            Int32Array::from(vec![0])
2048        );
2049
2050        assert_eq!(
2051            variable_size_list_values_row_number::<Int32Type>(
2052                &OffsetBuffer::from_lengths([2])
2053            ),
2054            Int32Array::from(vec![0, 0])
2055        );
2056    }
2057
2058    #[test]
2059    fn test_fsl_values_row_number() {
2060        assert_eq!(
2061            fsl_values_row_number(2, 3).unwrap(),
2062            Int32Array::from(vec![0, 0, 1, 1, 2, 2])
2063        );
2064
2065        assert_eq!(
2066            fsl_values_row_number(1, 3).unwrap(),
2067            Int32Array::from(vec![0, 1, 2])
2068        );
2069
2070        assert_eq!(
2071            fsl_values_row_number(2, 1).unwrap(),
2072            Int32Array::from(vec![0, 0])
2073        );
2074
2075        assert_eq!(
2076            fsl_values_row_number(2, 0).unwrap(),
2077            Int32Array::new_null(0),
2078        );
2079
2080        assert_eq!(
2081            fsl_values_row_number(0, 2).unwrap(),
2082            Int32Array::new_null(0),
2083        );
2084
2085        assert_eq!(
2086            fsl_values_row_number(0, 0).unwrap(),
2087            Int32Array::new_null(0),
2088        );
2089
2090        fsl_values_row_number(-1, 2).unwrap_err();
2091        fsl_values_row_number(-1, 0).unwrap_err();
2092    }
2093}