Skip to main content

arrow_row/
list.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
5use crate::{LengthTracker, RowConverter, Rows, SortField, fixed, null_sentinel};
6use arrow_array::{
7    Array, ArrayRef, FixedSizeListArray, GenericListArray, GenericListViewArray, MapArray,
8    OffsetSizeTrait, StructArray, new_null_array,
9};
10use arrow_buffer::{
11    ArrowNativeType, BooleanBuffer, MutableBuffer, NullBuffer, OffsetBuffer, ScalarBuffer,
12};
13use arrow_schema::{ArrowError, DataType, Fields, SortOptions};
14use std::{ops::Range, sync::Arc};
15
16pub(crate) trait GenericListArrayOrMap: Array {
17    type Offset: OffsetSizeTrait;
18
19    fn offsets(&self) -> &[Self::Offset];
20
21    unsafe fn from_parts_unchecked(
22        data_type: DataType,
23        offsets: Vec<Self::Offset>,
24        children: Vec<ArrayRef>,
25        null_buffer: Option<NullBuffer>,
26    ) -> Self
27    where
28        Self: Sized;
29}
30
31impl<O: OffsetSizeTrait> GenericListArrayOrMap for GenericListArray<O> {
32    type Offset = O;
33
34    fn offsets(&self) -> &[Self::Offset] {
35        self.value_offsets()
36    }
37
38    unsafe fn from_parts_unchecked(
39        data_type: DataType,
40        offsets: Vec<Self::Offset>,
41        children: Vec<ArrayRef>,
42        null_buffer: Option<NullBuffer>,
43    ) -> Self
44    where
45        Self: Sized,
46    {
47        let (DataType::List(field) | DataType::LargeList(field)) = data_type else {
48            unreachable!()
49        };
50
51        let child = children
52            .into_iter()
53            .next()
54            .expect("List arrays must have exactly one child array");
55
56        // SAFETY: Caller must ensure offsets are valid and correctly correspond to the children and null buffer
57        // the benefit here is to avoid validating that the offsets are monotonically increasing
58        let offset_buffer = unsafe { OffsetBuffer::new_unchecked(ScalarBuffer::from(offsets)) };
59        GenericListArray::<Self::Offset>::new(field, offset_buffer, child, null_buffer)
60    }
61}
62
63impl GenericListArrayOrMap for MapArray {
64    type Offset = i32;
65
66    fn offsets(&self) -> &[Self::Offset] {
67        self.value_offsets()
68    }
69
70    unsafe fn from_parts_unchecked(
71        data_type: DataType,
72        offsets: Vec<Self::Offset>,
73        children: Vec<ArrayRef>,
74        null_buffer: Option<NullBuffer>,
75    ) -> Self
76    where
77        Self: Sized,
78    {
79        let DataType::Map(entries_field, ordered) = data_type else {
80            unreachable!("data type must be Map for MapArray");
81        };
82
83        assert_eq!(
84            children.len(),
85            2,
86            "Map arrays must have exactly two child arrays for keys and values"
87        );
88
89        let DataType::Struct(fields) = entries_field.data_type() else {
90            unreachable!("Map entry type must be Struct");
91        };
92
93        let entries = StructArray::new(
94            fields.clone(),
95            children,
96            // Entries StructArray cannot have NullBuffer since nulls are represented at the Map level
97            None,
98        );
99
100        // SAFETY: Caller must ensure offsets are valid and correctly correspond to the children and null buffer
101        // the benefit here is to avoid validating that the offsets are monotonically increasing
102        let offset_buffer = unsafe { OffsetBuffer::new_unchecked(ScalarBuffer::from(offsets)) };
103
104        MapArray::new(entries_field, offset_buffer, entries, null_buffer, ordered)
105    }
106}
107
108pub(crate) fn compute_lengths<L: GenericListArrayOrMap>(
109    lengths: &mut [usize],
110    rows: &Rows,
111    array: &L,
112) {
113    let shift = array.offsets()[0].as_usize();
114
115    lengths
116        .iter_mut()
117        .zip(array.offsets().windows(2))
118        .enumerate()
119        .for_each(|(idx, (length, offsets))| {
120            let start = offsets[0].as_usize() - shift;
121            let end = offsets[1].as_usize() - shift;
122            let range = array.is_valid(idx).then_some(start..end);
123            *length += list_like_element_encoded_len(rows, range);
124        });
125}
126
127/// Encodes the provided [`GenericListArrayOrMap`] to `out` with the provided `SortOptions`
128///
129/// `rows` should contain the encoded child elements
130pub(crate) fn encode<L: GenericListArrayOrMap>(
131    data: &mut [u8],
132    offsets: &mut [usize],
133    rows: &Rows,
134    opts: SortOptions,
135    array: &L,
136) {
137    let shift = array.offsets()[0].as_usize();
138
139    offsets
140        .iter_mut()
141        .skip(1)
142        .zip(array.offsets().windows(2))
143        .enumerate()
144        .for_each(|(idx, (offset, offsets))| {
145            let start = offsets[0].as_usize() - shift;
146            let end = offsets[1].as_usize() - shift;
147            let range = array.is_valid(idx).then_some(start..end);
148            let out = &mut data[*offset..];
149            *offset += encode_one(out, rows, range, opts)
150        });
151}
152
153#[inline]
154fn encode_one(
155    out: &mut [u8],
156    rows: &Rows,
157    range: Option<Range<usize>>,
158    opts: SortOptions,
159) -> usize {
160    match range {
161        None => super::variable::encode_null(out, opts),
162        Some(range) if range.start == range.end => super::variable::encode_empty(out, opts),
163        Some(range) => {
164            let mut offset = 0;
165            for i in range {
166                let row = rows.row(i);
167                offset += super::variable::encode_one(&mut out[offset..], Some(row.data), opts);
168            }
169            offset += super::variable::encode_empty(&mut out[offset..], opts);
170            offset
171        }
172    }
173}
174
175/// Decodes an array from `rows` with the provided `options`
176///
177/// # Safety
178///
179/// `rows` must contain valid data for the provided `converter`
180pub(crate) unsafe fn decode<ListLikeImpl: GenericListArrayOrMap>(
181    converter: &RowConverter,
182    rows: &mut [&[u8]],
183    field: &SortField,
184    validate_utf8: bool,
185) -> Result<ListLikeImpl, ArrowError> {
186    let opts = field.options;
187
188    let mut values_bytes = 0;
189
190    let mut offset = 0;
191    let mut offsets = Vec::with_capacity(rows.len() + 1);
192    offsets.push(ListLikeImpl::Offset::usize_as(0));
193
194    for row in rows.iter_mut() {
195        let mut row_offset = 0;
196        loop {
197            let decoded = super::variable::decode_blocks(&row[row_offset..], opts, |x| {
198                values_bytes += x.len();
199            });
200            if decoded <= 1 {
201                offsets.push(ListLikeImpl::Offset::usize_as(offset));
202                break;
203            }
204            row_offset += decoded;
205            offset += 1;
206        }
207    }
208    ListLikeImpl::Offset::from_usize(offset).expect("overflow");
209
210    let nulls = crate::variable::decode_nulls_sentinel(rows, opts)?;
211
212    let mut values_offsets = Vec::with_capacity(offset);
213    let mut values_bytes = Vec::with_capacity(values_bytes);
214    for row in rows.iter_mut() {
215        let mut row_offset = 0;
216        loop {
217            let decoded = super::variable::decode_blocks(&row[row_offset..], opts, |x| {
218                values_bytes.extend_from_slice(x)
219            });
220            row_offset += decoded;
221            if decoded <= 1 {
222                break;
223            }
224            values_offsets.push(values_bytes.len());
225        }
226        *row = &row[row_offset..];
227    }
228
229    if opts.descending {
230        values_bytes.iter_mut().for_each(|o| *o = !*o);
231    }
232
233    let mut last_value_offset = 0;
234    let mut child_rows: Vec<_> = values_offsets
235        .into_iter()
236        .map(|offset| {
237            let v = &values_bytes[last_value_offset..offset];
238            last_value_offset = offset;
239            v
240        })
241        .collect();
242
243    let children = unsafe { converter.convert_raw(&mut child_rows, validate_utf8) }?;
244
245    // Since RowConverter flattens certain data types (i.e. Dictionary),
246    // we need to use updated data type instead of original field
247    let corrected_type = match &field.data_type {
248        DataType::List(inner_field) => {
249            assert_eq!(children.len(), 1);
250            DataType::List(Arc::new(
251                inner_field
252                    .as_ref()
253                    .clone()
254                    .with_data_type(children[0].data_type().clone()),
255            ))
256        }
257        DataType::LargeList(inner_field) => {
258            assert_eq!(children.len(), 1);
259            DataType::LargeList(Arc::new(
260                inner_field
261                    .as_ref()
262                    .clone()
263                    .with_data_type(children[0].data_type().clone()),
264            ))
265        }
266        DataType::Map(inner_field, ordered) => {
267            let DataType::Struct(entries_field) = inner_field.data_type() else {
268                return Err(ArrowError::InvalidArgumentError(format!(
269                    "Expected Map entry type to be Struct, found: {}",
270                    inner_field.data_type()
271                )));
272            };
273            assert_eq!(
274                children.len(),
275                2,
276                "Map arrays must have exactly two child arrays for keys and values"
277            );
278            let key_field = entries_field[0]
279                .as_ref()
280                .clone()
281                .with_data_type(children[0].data_type().clone());
282            let value_field = entries_field[1]
283                .as_ref()
284                .clone()
285                .with_data_type(children[1].data_type().clone());
286
287            let entries_fields = Fields::from(vec![key_field, value_field]);
288
289            DataType::Map(
290                Arc::new(
291                    inner_field
292                        .as_ref()
293                        .clone()
294                        .with_data_type(DataType::Struct(entries_fields)),
295                ),
296                *ordered,
297            )
298        }
299        _ => unreachable!(),
300    };
301
302    Ok(unsafe { ListLikeImpl::from_parts_unchecked(corrected_type, offsets, children, nulls) })
303}
304
305pub fn compute_lengths_fixed_size_list(
306    tracker: &mut LengthTracker,
307    rows: &Rows,
308    array: &FixedSizeListArray,
309) {
310    let value_length = array.value_length().as_usize();
311    tracker.push_variable((0..array.len()).map(|idx| {
312        match array.is_valid(idx) {
313            true => {
314                1 + ((idx * value_length)..(idx + 1) * value_length)
315                    .map(|child_idx| rows.row(child_idx).as_ref().len())
316                    .sum::<usize>()
317            }
318            false => 1,
319        }
320    }))
321}
322
323/// Encodes the provided `FixedSizeListArray` to `out` with the provided `SortOptions`
324///
325/// `rows` should contain the encoded child elements
326pub fn encode_fixed_size_list(
327    data: &mut [u8],
328    offsets: &mut [usize],
329    rows: &Rows,
330    opts: SortOptions,
331    array: &FixedSizeListArray,
332) {
333    let null_sentinel = null_sentinel(opts);
334    offsets
335        .iter_mut()
336        .skip(1)
337        .enumerate()
338        .for_each(|(idx, offset)| {
339            let value_length = array.value_length().as_usize();
340            match array.is_valid(idx) {
341                true => {
342                    data[*offset] = 0x01;
343                    *offset += 1;
344                    for child_idx in (idx * value_length)..(idx + 1) * value_length {
345                        let row = rows.row(child_idx);
346                        let end_offset = *offset + row.as_ref().len();
347                        data[*offset..end_offset].copy_from_slice(row.as_ref());
348                        *offset = end_offset;
349                    }
350                }
351                false => {
352                    data[*offset] = null_sentinel;
353                    *offset += 1;
354                }
355            }
356        })
357}
358
359/// Decodes a fixed size list array from `rows` with the provided `options`
360///
361/// # Safety
362///
363/// `rows` must contain valid data for the provided `converter`
364pub unsafe fn decode_fixed_size_list(
365    converter: &RowConverter,
366    rows: &mut [&[u8]],
367    field: &SortField,
368    validate_utf8: bool,
369    value_length: usize,
370) -> Result<FixedSizeListArray, ArrowError> {
371    let list_type = &field.data_type;
372    let DataType::FixedSizeList(element_field, size) = list_type else {
373        return Err(ArrowError::InvalidArgumentError(format!(
374            "Expected FixedSizeListArray, found: {list_type}",
375        )));
376    };
377
378    let num_rows = rows.len();
379    let nulls = fixed::try_decode_nulls(rows)?;
380
381    let null_element_encoded =
382        converter.convert_columns(&[new_null_array(element_field.data_type(), 1)])?;
383    let null_element_encoded = null_element_encoded.row(0);
384    let null_element_slice = null_element_encoded.as_ref();
385
386    let mut child_rows = Vec::new();
387    for row in rows {
388        let valid = row[0] == 1;
389        let mut row_offset = 1;
390        if !valid {
391            for _ in 0..value_length {
392                child_rows.push(null_element_slice);
393            }
394        } else {
395            for _ in 0..value_length {
396                let mut temp_child_rows = vec![&row[row_offset..]];
397                unsafe { converter.convert_raw(&mut temp_child_rows, validate_utf8) }?;
398                let decoded_bytes = row.len() - row_offset - temp_child_rows[0].len();
399                let next_offset = row_offset + decoded_bytes;
400                child_rows.push(&row[row_offset..next_offset]);
401                row_offset = next_offset;
402            }
403        }
404        *row = &row[row_offset..]; // Update row for the next decoder
405    }
406
407    let mut children = unsafe { converter.convert_raw(&mut child_rows, validate_utf8) }?;
408    assert_eq!(children.len(), 1);
409
410    // Since RowConverter flattens certain data types (i.e. Dictionary),
411    // we need to use updated data type instead of original field
412    let corrected_element_field = Arc::new(
413        element_field
414            .as_ref()
415            .clone()
416            .with_data_type(children[0].data_type().clone()),
417    );
418
419    FixedSizeListArray::try_new_with_length(
420        corrected_element_field,
421        *size,
422        children.pop().unwrap(),
423        nulls,
424        num_rows,
425    )
426}
427
428/// Computes the encoded length for a single list/map element given its child rows.
429///
430/// This is used by list types (List, LargeList, ListView, LargeListView) and by Map to determine
431/// the encoded length of a list element/map entry. For null elements, returns 1 (null sentinel only).
432/// For valid elements, returns 1 + the sum of padded lengths for each child row.
433#[inline]
434fn list_like_element_encoded_len(rows: &Rows, range: Option<Range<usize>>) -> usize {
435    match range {
436        None => 1,
437        Some(range) => {
438            1 + range
439                .map(|i| super::variable::padded_length(Some(rows.row(i).as_ref().len())))
440                .sum::<usize>()
441        }
442    }
443}
444
445/// Computes the encoded lengths for a `GenericListViewArray`
446///
447/// `rows` should contain the encoded child elements
448pub fn compute_lengths_list_view<O: OffsetSizeTrait>(
449    lengths: &mut [usize],
450    rows: &Rows,
451    array: &GenericListViewArray<O>,
452    shift: usize,
453) {
454    let offsets = array.value_offsets();
455    let sizes = array.value_sizes();
456
457    lengths.iter_mut().enumerate().for_each(|(idx, length)| {
458        let size = sizes[idx].as_usize();
459        let range = array.is_valid(idx).then(|| {
460            // For empty lists (size=0), offset may be arbitrary and could underflow when shifted.
461            // Use 0 as start since the range is empty anyway.
462            let start = if size > 0 {
463                offsets[idx].as_usize() - shift
464            } else {
465                0
466            };
467            start..start + size
468        });
469        *length += list_like_element_encoded_len(rows, range);
470    });
471}
472
473/// Encodes the provided `GenericListViewArray` to `out` with the provided `SortOptions`
474///
475/// `rows` should contain the encoded child elements
476pub fn encode_list_view<O: OffsetSizeTrait>(
477    data: &mut [u8],
478    out_offsets: &mut [usize],
479    rows: &Rows,
480    opts: SortOptions,
481    array: &GenericListViewArray<O>,
482    shift: usize,
483) {
484    let offsets = array.value_offsets();
485    let sizes = array.value_sizes();
486
487    out_offsets
488        .iter_mut()
489        .skip(1)
490        .enumerate()
491        .for_each(|(idx, offset)| {
492            let size = sizes[idx].as_usize();
493            let range = array.is_valid(idx).then(|| {
494                // For empty lists (size=0), offset may be arbitrary and could underflow when shifted.
495                // Use 0 as start since the range is empty anyway.
496                let start = if size > 0 {
497                    offsets[idx].as_usize() - shift
498                } else {
499                    0
500                };
501                start..start + size
502            });
503            let out = &mut data[*offset..];
504            *offset += encode_one(out, rows, range, opts)
505        });
506}
507
508/// Decodes a `GenericListViewArray` from `rows` with the provided `options`
509///
510/// # Safety
511///
512/// `rows` must contain valid data for the provided `converter`
513pub unsafe fn decode_list_view<O: OffsetSizeTrait>(
514    converter: &RowConverter,
515    rows: &mut [&[u8]],
516    field: &SortField,
517    validate_utf8: bool,
518) -> Result<GenericListViewArray<O>, ArrowError> {
519    let opts = field.options;
520
521    let mut values_bytes = 0;
522
523    let mut child_count = 0usize;
524    let mut list_sizes: Vec<O> = Vec::with_capacity(rows.len());
525
526    // First pass: count children and compute sizes
527    for row in rows.iter_mut() {
528        let mut row_offset = 0;
529        let mut list_size = 0usize;
530        loop {
531            let decoded = super::variable::decode_blocks(&row[row_offset..], opts, |x| {
532                values_bytes += x.len();
533            });
534            if decoded <= 1 {
535                list_sizes.push(O::usize_as(list_size));
536                break;
537            }
538            row_offset += decoded;
539            child_count += 1;
540            list_size += 1;
541        }
542    }
543    O::from_usize(child_count).expect("overflow");
544
545    let null_sentinel = null_sentinel(opts);
546    let mut null_count = 0;
547    let nulls = MutableBuffer::try_collect_bool(rows.len(), |x| {
548        let valid = rows[x][0] != null_sentinel;
549        null_count += !valid as usize;
550        valid
551    })
552    .map_err(|e| ArrowError::MemoryError(e.to_string()))?;
553
554    let mut values_offsets_vec = Vec::with_capacity(child_count);
555    let mut values_bytes = Vec::with_capacity(values_bytes);
556    for row in rows.iter_mut() {
557        let mut row_offset = 0;
558        loop {
559            let decoded = super::variable::decode_blocks(&row[row_offset..], opts, |x| {
560                values_bytes.extend_from_slice(x)
561            });
562            row_offset += decoded;
563            if decoded <= 1 {
564                break;
565            }
566            values_offsets_vec.push(values_bytes.len());
567        }
568        *row = &row[row_offset..];
569    }
570
571    if opts.descending {
572        values_bytes.iter_mut().for_each(|o| *o = !*o);
573    }
574
575    let mut last_value_offset = 0;
576    let mut child_rows: Vec<_> = values_offsets_vec
577        .into_iter()
578        .map(|offset| {
579            let v = &values_bytes[last_value_offset..offset];
580            last_value_offset = offset;
581            v
582        })
583        .collect();
584
585    let child = unsafe { converter.convert_raw(&mut child_rows, validate_utf8) }?;
586    assert_eq!(child.len(), 1);
587
588    let child_data = child[0].to_data();
589
590    // Technically ListViews don't have to have offsets follow each other precisely, but can be
591    // reused. However, because we cannot preserve that sharing within the row format, this is the
592    // best we can do.
593    let mut list_offsets: Vec<O> = Vec::with_capacity(rows.len());
594    let mut current_offset = O::usize_as(0);
595    for size in &list_sizes {
596        list_offsets.push(current_offset);
597        current_offset += *size;
598    }
599
600    // Since RowConverter flattens certain data types (i.e. Dictionary),
601    // we need to use updated data type instead of original field
602    let corrected_inner_field = match &field.data_type {
603        DataType::ListView(inner_field) | DataType::LargeListView(inner_field) => Arc::new(
604            inner_field
605                .as_ref()
606                .clone()
607                .with_data_type(child_data.data_type().clone()),
608        ),
609        _ => unreachable!(),
610    };
611
612    // SAFETY: null_count was computed correctly when building the nulls buffer above
613    let null_buffer = unsafe {
614        NullBuffer::new_unchecked(BooleanBuffer::new(nulls.into(), 0, rows.len()), null_count)
615    };
616
617    GenericListViewArray::try_new(
618        corrected_inner_field,
619        ScalarBuffer::from(list_offsets),
620        ScalarBuffer::from(list_sizes),
621        child[0].clone(),
622        Some(null_buffer).filter(|n| n.null_count() > 0),
623    )
624}