adriangb commented on code in PR #12184:
URL: https://github.com/apache/arrow-rs/pull/12184#discussion_r4722413756


##########
arrow-select/src/minify.rs:
##########
@@ -0,0 +1,2608 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+//! [`minify`]: Copy an array into buffers that hold only the data its rows 
reference
+//!
+//! Arrays often keep memory alive that their visible rows do not use:
+//!
+//! * A sliced array shares the buffers of the original, unsliced array.
+//! * A sliced list, map or byte array shares the full child array or value 
buffer.
+//! * A view array can reference a small part of large data buffers.
+//! * A dictionary can hold values that no key references.
+//! * A dense union can hold child rows that no row references.
+//!
+//! [`minify`] returns a logically equal array without this unused memory.
+//!
+//! # Reuse policy
+//!
+//! [`minify`] copies a buffer only when its allocation is larger than the
+//! visible data needs (rounded up to 64 bytes). Otherwise it reuses the buffer
+//! without a copy. This makes `minify` cheap on an array that is already
+//! minimal, and calling it twice copies nothing the second time.
+//!
+//! A buffer that other arrays share counts as too large when its allocation
+//! is larger than the visible data. `minify` copies it, so the total memory in
+//! use can grow until the other arrays drop the shared buffer.
+//!
+//! A buffer can also appear more than once inside `array`, for example in
+//! two struct columns over the same array, or in two dictionaries over the
+//! same values. Struct columns over the same rows of the same buffers share
+//! one minified column. In other cases `minify` can copy the buffer once per
+//! reference. If the result then uses more memory than `array` (beyond 64
+//! bytes per allocation), `minify` returns `array` unchanged.
+//!
+//! # Null rows
+//!
+//! `minify` gives every null row of a byte, list, map or list view array an
+//! empty value range, and every null row of a byte view array an empty view.
+//! The child array or value buffers then hold only the data of valid rows.
+//!
+//! An O(rows) check over the offsets and the null bitmap finds out if any null
+//! row has a non-empty range. If none has, `minify` copies or slices the
+//! referenced range in one piece. Otherwise it copies the ranges of each run 
of
+//! valid rows.
+//!
+//! # Limitations
+//!
+//! * `minify` does not deduplicate dictionary values or merge equal runs.
+//! * Null rows of a struct or fixed size list array keep their child data.
+//!   The child rows stay at the same positions, so `minify` cannot drop them.
+//! * The rows of a sparse union keep the data of all children, also of the
+//!   children that their type ids do not select.
+
+use std::collections::HashSet;
+use std::ops::Range;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::{
+    ArrowNativeType, BooleanBuffer, BooleanBufferBuilder, Buffer, NullBuffer, 
OffsetBuffer,
+    ScalarBuffer, bit_util,
+};
+use arrow_data::transform::{Capacities, MutableArrayData};
+use arrow_data::{ArrayData, ByteView, MAX_INLINE_VIEW_LEN};
+use arrow_schema::{
+    ArrowError, DataType, FieldRef, IntervalUnit, TimeUnit, UnionFields, 
UnionMode,
+};
+
+use crate::take::take;
+
+/// Returns an array that is logically equal to `array` and whose buffers hold
+/// only the data that its rows reference.
+///
+/// The result has an offset of zero, except when `minify` returns `array`
+/// unchanged because aliased buffers would make the result larger (see the
+/// [module documentation](self)). `minify` applies itself recursively to
+/// child arrays, dictionary values and run-end encoded values.
+///
+/// See the [module documentation](self) for the policy on when `minify`
+/// reuses a buffer instead of copying it.
+///
+/// # Example
+///
+/// ```
+/// # use arrow_array::{Array, Int32Array};
+/// # use arrow_select::minify::minify;
+/// let array = Int32Array::from_iter_values(0..1024);
+/// let sliced = array.slice(10, 4);
+/// // The slice keeps the whole 4 KiB buffer alive
+/// assert_eq!(sliced.get_buffer_memory_size(), 4096);
+///
+/// let minified = minify(&sliced).unwrap();
+/// assert_eq!(minified.as_ref(), &sliced as &dyn Array);
+/// assert_eq!(minified.get_buffer_memory_size(), 64);
+/// ```
+///
+/// # Errors
+///
+/// `minify` returns `InvalidArgumentError` for a time type with an invalid
+/// unit, a dictionary with an invalid key type and a run-end encoded array
+/// with an invalid run end type. It also returns the error of an array
+/// constructor that rejects the minified parts.
+pub fn minify(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
+    let minified = minify_inner(array)?;
+    // Buffers that `array` references more than once can be copied once per
+    // reference. Then `array` itself uses less memory. The slack of 64 bytes
+    // per allocation ignores the rounding of small allocations.
+    let (after, allocations) = allocated_memory(&minified.to_data());
+    let (before, _) = allocated_memory(&array.to_data());
+    if grew(before, after, allocations) {
+        return Ok(make_array(array.to_data()));
+    }
+    Ok(minified)
+}
+
+/// Returns `true` if `after` bytes in `allocations` allocations exceed
+/// `before` bytes by more than 64 bytes per allocation.
+fn grew(before: usize, after: usize, allocations: usize) -> bool {
+    after > before + 64 * allocations
+}
+
+/// Returns the capacity and the number of all distinct allocations that
+/// `data` and its children reference.
+fn allocated_memory(data: &ArrayData) -> (usize, usize) {
+    fn visit(data: &ArrayData, seen: &mut HashSet<*const u8>, total: &mut 
usize) {
+        let buffers = data
+            .buffers()
+            .iter()
+            .chain(data.nulls().map(|n| n.buffer()));
+        for b in buffers {
+            if seen.insert(b.data_ptr().as_ptr()) {
+                *total += b.capacity();
+            }
+        }
+        data.child_data().iter().for_each(|c| visit(c, seen, total));
+    }
+    let mut total = 0;
+    let mut seen = HashSet::new();
+    visit(data, &mut seen, &mut total);
+    (total, seen.len())
+}
+
+/// Returns `true` if `a` and `b` describe the same rows of the same buffers.
+fn same_data(a: &ArrayData, b: &ArrayData) -> bool {
+    let same_buffer = |x: &Buffer, y: &Buffer| x.as_ptr() == y.as_ptr() && 
x.len() == y.len();
+    let same_nulls = match (a.nulls(), b.nulls()) {
+        (None, None) => true,
+        (Some(x), Some(y)) => {
+            x.offset() == y.offset() && x.len() == y.len() && 
same_buffer(x.buffer(), y.buffer())
+        }
+        _ => false,
+    };
+    a.data_type() == b.data_type()
+        && a.len() == b.len()
+        && a.offset() == b.offset()
+        && same_nulls
+        && a.buffers().len() == b.buffers().len()
+        && a.buffers()
+            .iter()
+            .zip(b.buffers())
+            .all(|(x, y)| same_buffer(x, y))
+        && a.child_data().len() == b.child_data().len()
+        && a.child_data()
+            .iter()
+            .zip(b.child_data())
+            .all(|(x, y)| same_data(x, y))
+}
+
+fn minify_inner(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
+    macro_rules! primitive {
+        ($t:ty) => {
+            Ok(Arc::new(minify_primitive(array.as_primitive::<$t>())))
+        };
+    }
+    match array.data_type() {
+        DataType::Null => Ok(Arc::new(NullArray::new(array.len()))),
+        DataType::Int8 => primitive!(Int8Type),
+        DataType::Int16 => primitive!(Int16Type),
+        DataType::Int32 => primitive!(Int32Type),
+        DataType::Int64 => primitive!(Int64Type),
+        DataType::UInt8 => primitive!(UInt8Type),
+        DataType::UInt16 => primitive!(UInt16Type),
+        DataType::UInt32 => primitive!(UInt32Type),
+        DataType::UInt64 => primitive!(UInt64Type),
+        DataType::Float16 => primitive!(Float16Type),
+        DataType::Float32 => primitive!(Float32Type),
+        DataType::Float64 => primitive!(Float64Type),
+        DataType::Decimal32(_, _) => primitive!(Decimal32Type),
+        DataType::Decimal64(_, _) => primitive!(Decimal64Type),
+        DataType::Decimal128(_, _) => primitive!(Decimal128Type),
+        DataType::Decimal256(_, _) => primitive!(Decimal256Type),
+        DataType::Date32 => primitive!(Date32Type),
+        DataType::Date64 => primitive!(Date64Type),
+        DataType::Time32(TimeUnit::Second) => primitive!(Time32SecondType),
+        DataType::Time32(TimeUnit::Millisecond) => 
primitive!(Time32MillisecondType),
+        DataType::Time64(TimeUnit::Microsecond) => 
primitive!(Time64MicrosecondType),
+        DataType::Time64(TimeUnit::Nanosecond) => 
primitive!(Time64NanosecondType),
+        t @ (DataType::Time32(TimeUnit::Microsecond | TimeUnit::Nanosecond)
+        | DataType::Time64(TimeUnit::Second | TimeUnit::Millisecond)) => Err(
+            ArrowError::InvalidArgumentError(format!("invalid time unit in 
{t}")),
+        ),
+        DataType::Timestamp(TimeUnit::Second, _) => 
primitive!(TimestampSecondType),
+        DataType::Timestamp(TimeUnit::Millisecond, _) => 
primitive!(TimestampMillisecondType),
+        DataType::Timestamp(TimeUnit::Microsecond, _) => 
primitive!(TimestampMicrosecondType),
+        DataType::Timestamp(TimeUnit::Nanosecond, _) => 
primitive!(TimestampNanosecondType),
+        DataType::Duration(TimeUnit::Second) => primitive!(DurationSecondType),
+        DataType::Duration(TimeUnit::Millisecond) => 
primitive!(DurationMillisecondType),
+        DataType::Duration(TimeUnit::Microsecond) => 
primitive!(DurationMicrosecondType),
+        DataType::Duration(TimeUnit::Nanosecond) => 
primitive!(DurationNanosecondType),
+        DataType::Interval(IntervalUnit::YearMonth) => 
primitive!(IntervalYearMonthType),
+        DataType::Interval(IntervalUnit::DayTime) => 
primitive!(IntervalDayTimeType),
+        DataType::Interval(IntervalUnit::MonthDayNano) => 
primitive!(IntervalMonthDayNanoType),
+        DataType::Boolean => {
+            let array = array.as_boolean();
+            let values = minify_bool_buffer(array.values());
+            Ok(Arc::new(BooleanArray::new(
+                values,
+                minify_nulls(array.nulls()),
+            )))
+        }
+        DataType::Utf8 => 
Ok(Arc::new(minify_bytes(array.as_bytes::<Utf8Type>()))),
+        DataType::LargeUtf8 => 
Ok(Arc::new(minify_bytes(array.as_bytes::<LargeUtf8Type>()))),
+        DataType::Binary => 
Ok(Arc::new(minify_bytes(array.as_bytes::<BinaryType>()))),
+        DataType::LargeBinary => 
Ok(Arc::new(minify_bytes(array.as_bytes::<LargeBinaryType>()))),
+        DataType::Utf8View => Ok(Arc::new(minify_byte_view(
+            array.as_byte_view::<StringViewType>(),
+        ))),
+        DataType::BinaryView => Ok(Arc::new(minify_byte_view(
+            array.as_byte_view::<BinaryViewType>(),
+        ))),
+        DataType::FixedSizeBinary(size) => {
+            let array = array.as_fixed_size_binary();
+            let values = minify_buffer(array.values());
+            Ok(Arc::new(FixedSizeBinaryArray::try_new_with_len(
+                *size,
+                values,
+                minify_nulls(array.nulls()),
+                array.len(),
+            )?))
+        }
+        DataType::List(field) => minify_list(array.as_list::<i32>(), field),
+        DataType::LargeList(field) => minify_list(array.as_list::<i64>(), 
field),
+        DataType::ListView(field) => 
minify_list_view(array.as_list_view::<i32>(), field),
+        DataType::LargeListView(field) => 
minify_list_view(array.as_list_view::<i64>(), field),
+        DataType::FixedSizeList(field, size) => {
+            let array = array.as_fixed_size_list();
+            // `FixedSizeListArray::slice` already slices the child array
+            let values = minify_inner(array.values().as_ref())?;
+            Ok(Arc::new(FixedSizeListArray::try_new_with_length(
+                Arc::clone(field),
+                *size,
+                values,
+                minify_nulls(array.nulls()),
+                array.len(),
+            )?))
+        }
+        DataType::Map(field, ordered) => {
+            let array = array.as_map();
+            let (offsets, entries) =
+                minify_list_child(array.offsets(), array.entries(), 
array.nulls())?;
+            Ok(Arc::new(MapArray::try_new(
+                Arc::clone(field),
+                offsets,
+                entries.as_struct().clone(),
+                minify_nulls(array.nulls()),
+                *ordered,
+            )?))
+        }
+        DataType::Struct(fields) => {
+            let array = array.as_struct();
+            // `StructArray::slice` already slices the child arrays
+            // Columns over the same data share one minified column
+            let mut done: Vec<(ArrayData, ArrayRef)> = vec![];
+            let mut columns = Vec::with_capacity(array.num_columns());
+            for c in array.columns() {
+                let data = c.to_data();
+                let column = match done.iter().find(|(d, _)| same_data(d, 
&data)) {
+                    Some((_, m)) => Arc::clone(m),
+                    None => {
+                        let m = minify_inner(c.as_ref())?;
+                        done.push((data, Arc::clone(&m)));
+                        m
+                    }
+                };
+                columns.push(column);
+            }
+            Ok(Arc::new(StructArray::try_new_with_length(
+                fields.clone(),
+                columns,
+                minify_nulls(array.nulls()),
+                array.len(),
+            )?))
+        }
+        DataType::Union(fields, mode) => minify_union(array.as_union(), 
fields, *mode),
+        DataType::Dictionary(key, _) => match key.as_ref() {
+            DataType::Int8 => 
minify_dictionary(array.as_dictionary::<Int8Type>()),
+            DataType::Int16 => 
minify_dictionary(array.as_dictionary::<Int16Type>()),
+            DataType::Int32 => 
minify_dictionary(array.as_dictionary::<Int32Type>()),
+            DataType::Int64 => 
minify_dictionary(array.as_dictionary::<Int64Type>()),
+            DataType::UInt8 => 
minify_dictionary(array.as_dictionary::<UInt8Type>()),
+            DataType::UInt16 => 
minify_dictionary(array.as_dictionary::<UInt16Type>()),
+            DataType::UInt32 => 
minify_dictionary(array.as_dictionary::<UInt32Type>()),
+            DataType::UInt64 => 
minify_dictionary(array.as_dictionary::<UInt64Type>()),
+            t => Err(ArrowError::InvalidArgumentError(format!(
+                "invalid dictionary key type {t}"
+            ))),
+        },
+        DataType::RunEndEncoded(run_ends, _) => match run_ends.data_type() {
+            DataType::Int16 => minify_run(array.as_run::<Int16Type>()),
+            DataType::Int32 => minify_run(array.as_run::<Int32Type>()),
+            DataType::Int64 => minify_run(array.as_run::<Int64Type>()),
+            t => Err(ArrowError::InvalidArgumentError(format!(
+                "invalid run end type {t}"
+            ))),
+        },
+    }
+}
+
+/// Returns `true` if `buffer` owns an allocation that is larger than its
+/// length (rounded up to 64 bytes).
+fn is_oversized(buffer: &Buffer) -> bool {
+    buffer.capacity() > bit_util::round_upto_multiple_of_64(buffer.len())
+}
+
+/// Returns `buffer`, or a copy of `buffer` if its allocation is oversized.
+fn minify_buffer(buffer: &Buffer) -> Buffer {
+    if is_oversized(buffer) {
+        Buffer::from_slice_ref(buffer.as_slice())
+    } else {
+        buffer.clone()
+    }
+}
+
+fn minify_scalar_buffer<T: ArrowNativeType>(buffer: &ScalarBuffer<T>) -> 
ScalarBuffer<T> {
+    ScalarBuffer::new(minify_buffer(buffer.inner()), 0, buffer.len())
+}
+
+fn minify_bool_buffer(buffer: &BooleanBuffer) -> BooleanBuffer {
+    // `sliced` copies the bits when the offset is not a multiple of 8.
+    // Otherwise it returns a zero-copy slice, which `minify_buffer` checks.
+    BooleanBuffer::new(minify_buffer(&buffer.sliced()), 0, buffer.len())
+}
+
+/// Copies the null buffer if needed, and drops it if it has no nulls.
+fn minify_nulls(nulls: Option<&NullBuffer>) -> Option<NullBuffer> {
+    let nulls = nulls.filter(|n| n.null_count() > 0)?;
+    let buffer = minify_bool_buffer(nulls.inner());
+    // SAFETY: the bits and so the null count do not change
+    Some(unsafe { NullBuffer::new_unchecked(buffer, nulls.null_count()) })
+}
+
+/// Returns offsets that start at zero, plus the start and end of the child
+/// range that the original offsets reference.
+fn rebase_offsets<O: OffsetSizeTrait>(
+    offsets: &OffsetBuffer<O>,
+) -> (OffsetBuffer<O>, usize, usize) {
+    let start = offsets[0];
+    let end = offsets[offsets.len() - 1];
+    let values = if start == O::zero() {
+        minify_scalar_buffer(offsets.inner())
+    } else {
+        offsets.iter().map(|o| *o - start).collect()
+    };
+    // SAFETY: subtracting the first offset keeps the offsets monotonic and 
non-negative
+    let offsets = unsafe { OffsetBuffer::new_unchecked(values) };
+    (offsets, start.as_usize(), end.as_usize())
+}
+
+/// Returns the null buffer if a null row has a non-empty range in `offsets`.
+///
+/// Offsets never decrease, so a run of null rows has only empty ranges if
+/// the offsets at its start and end are equal. The check costs O(runs).
+fn nulls_with_ranges<'a, O: OffsetSizeTrait>(
+    offsets: &OffsetBuffer<O>,
+    nulls: Option<&'a NullBuffer>,
+) -> Option<&'a NullBuffer> {
+    let nulls = nulls.filter(|n| n.null_count() > 0)?;
+    let mut null_start = 0;
+    for (start, end) in nulls.valid_slices().chain([(nulls.len(), 
nulls.len())]) {
+        if offsets[null_start] != offsets[start] {
+            return Some(nulls);
+        }
+        null_start = end;
+    }
+    None
+}
+
+/// Returns offsets that give every null row an empty range, plus the child
+/// ranges of the valid rows. Adjacent child ranges merge into one range.
+fn compact_offsets<O: OffsetSizeTrait>(
+    offsets: &OffsetBuffer<O>,
+    nulls: &NullBuffer,
+) -> (OffsetBuffer<O>, Vec<Range<usize>>) {
+    let mut ranges: Vec<Range<usize>> = vec![];
+    let mut compacted = Vec::with_capacity(offsets.len());
+    compacted.push(O::zero());
+    let mut null_start = 0;
+    for (s, e) in nulls.valid_slices() {
+        let last = compacted[compacted.len() - 1];
+        compacted.extend(std::iter::repeat_n(last, s - null_start));
+        let base = offsets[s];
+        compacted.extend(offsets[s + 1..=e].iter().map(|o| last + (*o - 
base)));
+        null_start = e;
+
+        push_range(&mut ranges, base.as_usize()..offsets[e].as_usize());
+    }
+    let last = compacted[compacted.len() - 1];
+    compacted.resize(offsets.len(), last);
+    // SAFETY: the offsets start at zero and never decrease
+    let offsets = unsafe { OffsetBuffer::new_unchecked(compacted.into()) };
+    (offsets, ranges)
+}
+
+/// Returns `true` if [`gather_ranges`] gathers `data_type` by its parts
+/// instead of with `MutableArrayData`.
+///
+/// `MutableArrayData` copies a child row that several rows share once per
+/// row. Dense union rows can share child rows, and list views can overlap.
+/// `MutableArrayData` also splits the runs of a run-end encoded array in
+/// its own way, so the result of `minify` would depend on the gather path.
+fn gathers_parts(data_type: &DataType) -> bool {
+    match data_type {
+        DataType::Union(_, UnionMode::Dense)
+        | DataType::ListView(_)
+        | DataType::LargeListView(_)
+        | DataType::RunEndEncoded(_, _) => true,
+        DataType::List(f)
+        | DataType::LargeList(f)
+        | DataType::FixedSizeList(f, _)
+        | DataType::Map(f, _) => gathers_parts(f.data_type()),
+        DataType::Struct(fields) => fields.iter().any(|f| 
gathers_parts(f.data_type())),
+        DataType::Union(fields, UnionMode::Sparse) => {
+            fields.iter().any(|(_, f)| gathers_parts(f.data_type()))
+        }
+        DataType::Dictionary(_, values) => gathers_parts(values),
+        DataType::Null
+        | DataType::Boolean
+        | DataType::Int8
+        | DataType::Int16
+        | DataType::Int32
+        | DataType::Int64
+        | DataType::UInt8
+        | DataType::UInt16
+        | DataType::UInt32
+        | DataType::UInt64
+        | DataType::Float16
+        | DataType::Float32
+        | DataType::Float64
+        | DataType::Decimal32(_, _)
+        | DataType::Decimal64(_, _)
+        | DataType::Decimal128(_, _)
+        | DataType::Decimal256(_, _)
+        | DataType::Date32
+        | DataType::Date64
+        | DataType::Time32(_)
+        | DataType::Time64(_)
+        | DataType::Timestamp(_, _)
+        | DataType::Duration(_)
+        | DataType::Interval(_)
+        | DataType::Utf8
+        | DataType::LargeUtf8
+        | DataType::Binary
+        | DataType::LargeBinary
+        | DataType::Utf8View
+        | DataType::BinaryView
+        | DataType::FixedSizeBinary(_) => false,
+    }
+}
+
+/// Appends `range` to `ranges`, and merges it with the last range if they
+/// are adjacent. Skips an empty range.
+fn push_range(ranges: &mut Vec<Range<usize>>, range: Range<usize>) {
+    match ranges.last_mut() {
+        Some(r) if r.end == range.start => r.end = range.end,
+        _ if range.start < range.end => ranges.push(range),
+        _ => {}
+    }
+}
+
+/// Copies `ranges` of `values` back to back into a new minified array.
+///
+/// See [`gathers_parts`] for the types that `gather_ranges` gathers without
+/// `MutableArrayData`. It selects their rows without a copy of the children,
+/// and `minify` then keeps shared child rows shared.
+fn gather_ranges(values: &dyn Array, ranges: &[Range<usize>]) -> 
Result<ArrayRef, ArrowError> {
+    let len = ranges.iter().map(|r| r.len()).sum();
+    if !gathers_parts(values.data_type()) {
+        return gather_ranges_copy(values, ranges, len);
+    }
+    let gathered: ArrayRef = match values.data_type() {
+        DataType::Union(fields, UnionMode::Dense) => 
Arc::new(select_dense_union(
+            values.as_union(),
+            fields,
+            ranges.iter().flat_map(|r| r.clone()),
+        )),
+        // `take` keeps the child of a list view
+        DataType::ListView(_) | DataType::LargeListView(_) => {
+            let indices = ranges.iter().flat_map(|r| r.start as u64..r.end as 
u64);
+            take(values, &UInt64Array::from_iter_values(indices), None)?
+        }
+        DataType::List(field) => gather_list(values.as_list::<i32>(), field, 
ranges)?,
+        DataType::LargeList(field) => gather_list(values.as_list::<i64>(), 
field, ranges)?,
+        DataType::Map(field, ordered) => {
+            let array = values.as_map();
+            let (offsets, child_ranges) = gather_offsets(array.offsets(), 
array.nulls(), ranges);
+            let entries = gather_ranges(array.entries(), &child_ranges)?;
+            Arc::new(MapArray::try_new(
+                Arc::clone(field),
+                offsets,
+                entries.as_struct().clone(),
+                gather_nulls(array.nulls(), ranges, len),
+                *ordered,
+            )?)
+        }
+        DataType::FixedSizeList(field, size) => {
+            let array = values.as_fixed_size_list();
+            let size = *size as usize;
+            let child_ranges: Vec<_> = ranges
+                .iter()
+                .map(|r| r.start * size..r.end * size)
+                .collect();
+            Arc::new(FixedSizeListArray::try_new_with_length(
+                Arc::clone(field),
+                size as i32,
+                gather_ranges(array.values().as_ref(), &child_ranges)?,
+                gather_nulls(array.nulls(), ranges, len),
+                len,
+            )?)
+        }
+        DataType::Struct(fields) => {
+            let array = values.as_struct();
+            let columns = array
+                .columns()
+                .iter()
+                .map(|c| gather_ranges(c.as_ref(), ranges))
+                .collect::<Result<Vec<_>, _>>()?;
+            Arc::new(StructArray::try_new_with_length(
+                fields.clone(),
+                columns,
+                gather_nulls(array.nulls(), ranges, len),
+                len,
+            )?)
+        }
+        DataType::Union(fields, UnionMode::Sparse) => {
+            let array = values.as_union();
+            let type_ids = ranges
+                .iter()
+                .flat_map(|r| array.type_ids()[r.clone()].iter().copied())
+                .collect();
+            let children = fields
+                .iter()
+                .map(|(type_id, _)| 
gather_ranges(array.child(type_id).as_ref(), ranges))
+                .collect::<Result<Vec<_>, _>>()?;
+            // SAFETY: each row keeps its type id and its row in every child
+            Arc::new(unsafe { UnionArray::new_unchecked(fields.clone(), 
type_ids, None, children) })
+        }
+        DataType::RunEndEncoded(run_ends, _) => match run_ends.data_type() {
+            DataType::Int16 => gather_run(values.as_run::<Int16Type>(), 
ranges)?,
+            DataType::Int32 => gather_run(values.as_run::<Int32Type>(), 
ranges)?,
+            DataType::Int64 => gather_run(values.as_run::<Int64Type>(), 
ranges)?,
+            t => {
+                return Err(ArrowError::InvalidArgumentError(format!(
+                    "invalid run end type {t}"
+                )));
+            }
+        },
+        // `MutableArrayData` keeps the values of a dictionary, and `minify`
+        // prunes them afterwards. `gathers_parts` returns `false` for the
+        // flat types, so they do not reach this match.
+        DataType::Dictionary(_, _)
+        | DataType::Null
+        | DataType::Boolean
+        | DataType::Int8
+        | DataType::Int16
+        | DataType::Int32
+        | DataType::Int64
+        | DataType::UInt8
+        | DataType::UInt16
+        | DataType::UInt32
+        | DataType::UInt64
+        | DataType::Float16
+        | DataType::Float32
+        | DataType::Float64
+        | DataType::Decimal32(_, _)
+        | DataType::Decimal64(_, _)
+        | DataType::Decimal128(_, _)
+        | DataType::Decimal256(_, _)
+        | DataType::Date32
+        | DataType::Date64
+        | DataType::Time32(_)
+        | DataType::Time64(_)
+        | DataType::Timestamp(_, _)
+        | DataType::Duration(_)
+        | DataType::Interval(_)
+        | DataType::Utf8
+        | DataType::LargeUtf8
+        | DataType::Binary
+        | DataType::LargeBinary
+        | DataType::Utf8View
+        | DataType::BinaryView
+        | DataType::FixedSizeBinary(_) => return gather_ranges_copy(values, 
ranges, len),
+    };
+    minify_inner(gathered.as_ref())
+}
+
+/// Copies `ranges` of `values` with `MutableArrayData`.
+fn gather_ranges_copy(
+    values: &dyn Array,
+    ranges: &[Range<usize>],
+    len: usize,
+) -> Result<ArrayRef, ArrowError> {
+    let data = values.to_data();
+    // Exact byte capacities let `minify` reuse the gathered buffers
+    fn bytes<O: OffsetSizeTrait>(data: &ArrayData, ranges: &[Range<usize>]) -> 
usize {
+        let o = data.buffer::<O>(0);
+        ranges
+            .iter()
+            .map(|r| (o[r.end] - o[r.start]).as_usize())
+            .sum()
+    }
+    let capacities = match values.data_type() {
+        DataType::Utf8 | DataType::Binary => {
+            Capacities::Binary(len, Some(bytes::<i32>(&data, ranges)))
+        }
+        DataType::LargeUtf8 | DataType::LargeBinary => {
+            Capacities::Binary(len, Some(bytes::<i64>(&data, ranges)))
+        }
+        _ => Capacities::Array(len),
+    };
+    let mut mutable = MutableArrayData::with_capacities(vec![&data], false, 
capacities);
+    for r in ranges {
+        mutable.try_extend(0, r.start, r.end)?;
+    }
+    minify_inner(make_array(mutable.freeze()).as_ref())
+}
+
+/// Returns the offsets of `ranges` of rows back to back, plus the child
+/// ranges that the valid rows reference. Null rows get an empty range, as in
+/// [`compact_offsets`], so that `minify` of the result gathers nothing again.
+fn gather_offsets<O: OffsetSizeTrait>(
+    offsets: &OffsetBuffer<O>,
+    nulls: Option<&NullBuffer>,
+    ranges: &[Range<usize>],
+) -> (OffsetBuffer<O>, Vec<Range<usize>>) {
+    let mut gathered = Vec::with_capacity(ranges.iter().map(|r| 
r.len()).sum::<usize>() + 1);
+    gathered.push(O::zero());
+    let mut child_ranges = vec![];
+    let mut extend = |start: usize, end: usize, valid: bool| {
+        let last = gathered[gathered.len() - 1];
+        if valid {
+            let base = offsets[start];
+            gathered.extend(offsets[start + 1..=end].iter().map(|o| last + (*o 
- base)));
+            push_range(&mut child_ranges, 
base.as_usize()..offsets[end].as_usize());
+        } else {
+            gathered.extend(std::iter::repeat_n(last, end - start));
+        }
+    };
+    let nulls = nulls.filter(|n| n.null_count() > 0);
+    for r in ranges {
+        match nulls {
+            None => extend(r.start, r.end, true),
+            Some(nulls) => {
+                let mut null_start = r.start;
+                for (s, e) in nulls.inner().slice(r.start, 
r.len()).set_slices() {
+                    extend(null_start, r.start + s, false);
+                    extend(r.start + s, r.start + e, true);
+                    null_start = r.start + e;
+                }
+                extend(null_start, r.end, false);
+            }
+        }
+    }
+    // SAFETY: the offsets start at zero and never decrease
+    let offsets = unsafe { OffsetBuffer::new_unchecked(gathered.into()) };
+    (offsets, child_ranges)
+}
+
+fn gather_list<O: OffsetSizeTrait>(
+    array: &GenericListArray<O>,
+    field: &FieldRef,
+    ranges: &[Range<usize>],
+) -> Result<ArrayRef, ArrowError> {
+    let len = ranges.iter().map(|r| r.len()).sum();
+    let (offsets, child_ranges) = gather_offsets(array.offsets(), 
array.nulls(), ranges);
+    let values = gather_ranges(array.values().as_ref(), &child_ranges)?;
+    let nulls = gather_nulls(array.nulls(), ranges, len);
+    Ok(Arc::new(GenericListArray::<O>::try_new(
+        Arc::clone(field),
+        offsets,
+        values,
+        nulls,
+    )?))
+}
+
+fn gather_run<R: RunEndIndexType>(
+    array: &RunArray<R>,
+    ranges: &[Range<usize>],
+) -> Result<ArrayRef, ArrowError> {
+    let mut run_ends = vec![];
+    let mut value_ranges = vec![];
+    let mut len = 0;
+    for r in ranges.iter().filter(|r| !r.is_empty()) {
+        let slice = array.slice(r.start, r.len());
+        let ends = slice.run_ends();
+        let (start, end) = (
+            ends.get_start_physical_index(),
+            ends.get_end_physical_index(),
+        );
+        let mut sliced = ends.sliced_values().map(|e| len + e.as_usize());
+        // A range that starts in the run where the previous range ended
+        // extends that run. Otherwise every range that hits a long run would
+        // copy the run value again.
+        if continues_run(&value_ranges, start) {
+            let first = sliced.next().expect("non-empty range");
+            *run_ends.last_mut().expect("previous run") = 
R::Native::usize_as(first);
+            push_range(&mut value_ranges, start + 1..end + 1);
+        } else {
+            push_range(&mut value_ranges, start..end + 1);
+        }
+        run_ends.extend(sliced.map(R::Native::usize_as));
+        len += r.len();
+    }
+    let values = gather_ranges(array.values().as_ref(), &value_ranges)?;
+    let run_ends = PrimitiveArray::<R>::from_iter_values(run_ends);
+    Ok(Arc::new(RunArray::<R>::try_new(
+        &run_ends,
+        values.as_ref(),
+    )?))
+}
+
+/// Returns `true` if the last gathered value range ends with run `start`.
+fn continues_run(value_ranges: &[Range<usize>], start: usize) -> bool {
+    value_ranges.last().is_some_and(|v| v.end == start + 1)
+}
+
+fn gather_nulls(
+    nulls: Option<&NullBuffer>,
+    ranges: &[Range<usize>],
+    len: usize,
+) -> Option<NullBuffer> {
+    let nulls = nulls.filter(|n| n.null_count() > 0)?;
+    let mut builder = BooleanBufferBuilder::new(len);
+    for r in ranges {
+        builder.append_buffer(&nulls.inner().slice(r.start, r.len()));
+    }
+    Some(NullBuffer::new(builder.finish()))
+}
+
+/// Returns the dense union of `rows` of `array`. The result shares the
+/// children of `array`.
+fn select_dense_union(
+    array: &UnionArray,
+    fields: &UnionFields,
+    rows: impl Iterator<Item = usize> + Clone,
+) -> UnionArray {
+    let offsets = array.offsets().expect("dense union has offsets");
+    let type_ids = rows.clone().map(|i| array.type_ids()[i]).collect();
+    let offsets = rows.map(|i| offsets[i]).collect();
+    let children = fields
+        .iter()
+        .map(|(type_id, _)| Arc::clone(array.child(type_id)))
+        .collect();
+    // SAFETY: each row keeps its type id and its offset into the same child
+    unsafe { UnionArray::new_unchecked(fields.clone(), type_ids, 
Some(offsets), children) }
+}
+
+/// Returns minified offsets and child for a list or map array.
+fn minify_list_child<O: OffsetSizeTrait>(
+    offsets: &OffsetBuffer<O>,
+    values: &dyn Array,
+    nulls: Option<&NullBuffer>,
+) -> Result<(OffsetBuffer<O>, ArrayRef), ArrowError> {
+    match nulls_with_ranges(offsets, nulls) {
+        None => {
+            let (offsets, start, end) = rebase_offsets(offsets);
+            Ok((offsets, minify_inner(&values.slice(start, end - start))?))
+        }
+        Some(nulls) => {
+            let (offsets, ranges) = compact_offsets(offsets, nulls);
+            Ok((offsets, gather_ranges(values, &ranges)?))
+        }
+    }
+}
+
+fn minify_primitive<T: ArrowPrimitiveType>(array: &PrimitiveArray<T>) -> 
PrimitiveArray<T> {
+    PrimitiveArray::<T>::new(
+        minify_scalar_buffer(array.values()),
+        minify_nulls(array.nulls()),
+    )
+    .with_data_type(array.data_type().clone())
+}
+
+fn minify_bytes<T: ByteArrayType>(array: &GenericByteArray<T>) -> 
GenericByteArray<T> {
+    let (offsets, values) = match nulls_with_ranges(array.offsets(), 
array.nulls()) {
+        None => {
+            let (offsets, start, end) = rebase_offsets(array.offsets());
+            let values = 
minify_buffer(&array.values().slice_with_length(start, end - start));
+            (offsets, values)
+        }
+        Some(nulls) => {
+            let (offsets, ranges) = compact_offsets(array.offsets(), nulls);
+            let bytes = array.values().as_slice();
+            let mut values = Vec::with_capacity(offsets[offsets.len() - 
1].as_usize());
+            for r in ranges {
+                values.extend_from_slice(&bytes[r]);
+            }
+            (offsets, Buffer::from_vec(values))
+        }
+    };
+    // SAFETY: the offsets and values describe the same byte strings as before
+    unsafe { GenericByteArray::new_unchecked(offsets, values, 
minify_nulls(array.nulls())) }
+}
+
+/// The out-of-line bytes that the valid rows of a view array reference.
+struct ViewData {
+    /// The disjoint, sorted ranges as `(buffer index, start, end)`. Bytes
+    /// that several views share appear once.
+    merged: Vec<(u32, usize, usize)>,
+    /// The bytes in `merged` per data buffer
+    referenced: Vec<usize>,
+    /// `true` if a null row has an out-of-line view
+    null_views: bool,
+}
+
+/// Merges the out-of-line ranges of the valid views of `array`.
+///
+/// Null rows reference nothing. `minify` gives them an empty view, as it
+/// gives null rows of a byte array an empty range.
+fn view_data<T: ByteViewType + ?Sized>(
+    array: &GenericByteViewArray<T>,
+    nulls: Option<&NullBuffer>,
+) -> ViewData {
+    let mut ranges = vec![];
+    let mut null_views = false;
+    for (i, v) in array.views().iter().enumerate() {
+        let len = *v as u32;
+        if len <= MAX_INLINE_VIEW_LEN {
+            continue;
+        }
+        if nulls.is_some_and(|n| n.is_null(i)) {
+            null_views = true;
+            continue;
+        }
+        let view = ByteView::from(*v);
+        // A data buffer can be longer than `u32::MAX`, so the end can 
overflow `u32`
+        let start = view.offset as usize;
+        ranges.push((view.buffer_index, start, start + len as usize));
+    }
+    // Builders and `gc` write views in order, so the sort is often not needed
+    if !ranges.is_sorted() {
+        ranges.sort_unstable();
+    }
+    let mut merged: Vec<(u32, usize, usize)> = vec![];
+    for (b, s, e) in ranges {
+        match merged.last_mut() {
+            Some((mb, _, me)) if *mb == b && s <= *me => *me = (*me).max(e),
+            _ => merged.push((b, s, e)),
+        }
+    }
+    let mut referenced = vec![0; array.data_buffers().len()];
+    for (b, s, e) in &merged {
+        referenced[*b as usize] += e - s;
+    }
+    ViewData {
+        merged,
+        referenced,
+        null_views,
+    }
+}
+
+/// Returns `true` if `minify` keeps `buffer`, a data buffer whose valid
+/// views reference `referenced` distinct bytes. The views must reference
+/// every byte, and the allocation must not be oversized.
+fn keeps_view_buffer(buffer: &Buffer, referenced: usize) -> bool {
+    referenced > 0 && referenced == buffer.len() && !is_oversized(buffer)
+}
+
+/// Byte views can share bytes, appear out of order and leave gaps in the
+/// data buffers.
+///
+/// `minify` keeps each data buffer whose bytes the valid views all reference.
+/// It copies the referenced ranges of the other buffers back to back into new
+/// buffers, and moves each view to the copy of its range. Views that share
+/// bytes keep sharing them. Unreferenced buffers go away.
+fn minify_byte_view<T: ByteViewType + ?Sized>(
+    array: &GenericByteViewArray<T>,
+) -> GenericByteViewArray<T> {
+    let nulls = minify_nulls(array.nulls());
+    let ViewData {
+        merged,
+        referenced,
+        null_views,
+    } = view_data(array, nulls.as_ref());
+    let old_buffers = array.data_buffers();
+    let kept: Vec<bool> = old_buffers
+        .iter()
+        .zip(&referenced)
+        .map(|(b, r)| keeps_view_buffer(b, *r))
+        .collect();
+    if !null_views && kept.iter().all(|k| *k) {
+        let views = minify_scalar_buffer(array.views());
+        // SAFETY: the views, data buffers and null bits stay the same
+        return unsafe { GenericByteViewArray::new_unchecked(views, 
old_buffers.clone(), nulls) };
+    }
+
+    // The new index of each kept buffer
+    let mut new_index = vec![0u32; old_buffers.len()];
+    let mut buffers = vec![];
+    for (i, b) in old_buffers.iter().enumerate().filter(|(i, _)| kept[*i]) {
+        new_index[i] = buffers.len() as u32;
+        buffers.push(b.clone());
+    }
+    // The new buffer index and offset of each copied range in `merged`
+    let copied: Vec<usize> = (0..merged.len())
+        .filter(|i| !kept[merged[*i].0 as usize])
+        .collect();
+    let mut moved = vec![(0u32, 0u32); merged.len()];
+    let mut start = 0;
+    while start < copied.len() {
+        // A view offset is a `u32`. `gc` limits a buffer to `i32::MAX` bytes.
+        let mut end = start;
+        let mut len = 0usize;
+        while end < copied.len() {
+            let (_, s, e) = merged[copied[end]];
+            let range_len = e - s;
+            if end > start && len + range_len > i32::MAX as usize {
+                break;
+            }
+            len += range_len;
+            end += 1;
+        }
+        let mut bytes = Vec::with_capacity(len);
+        for i in &copied[start..end] {
+            let (b, s, e) = merged[*i];
+            moved[*i] = (buffers.len() as u32, bytes.len() as u32);
+            bytes.extend_from_slice(&old_buffers[b as usize][s..e]);
+        }
+        buffers.push(Buffer::from_vec(bytes));
+        start = end;
+    }
+
+    let views = array
+        .views()
+        .iter()
+        .enumerate()
+        .map(|(i, v)| {
+            let len = *v as u32;
+            if len <= MAX_INLINE_VIEW_LEN {
+                return *v;
+            }
+            if nulls.as_ref().is_some_and(|n| n.is_null(i)) {
+                return 0;
+            }
+            let view = ByteView::from(*v);
+            let (b, o) = (view.buffer_index, view.offset);
+            if kept[b as usize] {
+                return view.with_buffer_index(new_index[b as usize]).as_u128();
+            }
+            let r = merged.partition_point(|(mb, ms, _)| (*mb, *ms) <= (b, o 
as usize)) - 1;
+            let (new_buffer, base) = moved[r];
+            view.with_buffer_index(new_buffer)
+                .with_offset(base + (o as usize - merged[r].1) as u32)
+                .as_u128()
+        })
+        .collect();
+    // SAFETY: every view of a valid row points at a copy of its bytes or at
+    // its kept buffer, and null rows have an empty view
+    unsafe { GenericByteViewArray::new_unchecked(views, buffers.into(), nulls) 
}
+}
+
+fn minify_list<O: OffsetSizeTrait>(
+    array: &GenericListArray<O>,
+    field: &FieldRef,
+) -> Result<ArrayRef, ArrowError> {
+    let (offsets, values) = minify_list_child(array.offsets(), array.values(), 
array.nulls())?;
+    Ok(Arc::new(GenericListArray::<O>::try_new(
+        Arc::clone(field),
+        offsets,
+        values,
+        minify_nulls(array.nulls()),
+    )?))
+}
+
+/// The child rows that a set of list views references.
+struct ListViewChild {
+    /// The disjoint, sorted child ranges of the valid non-empty views
+    merged: Vec<Range<usize>>,
+    /// `true` if a null view has a non-zero offset or size
+    null_views: bool,
+    /// The largest offset of an empty valid view. Validation requires it to
+    /// lie inside the child, so the child slice must not cut it off.
+    empty_end: usize,
+}
+
+/// Merges the child ranges of `views`, given as `(valid, offset, size)`.
+fn list_view_child(views: impl Iterator<Item = (bool, usize, usize)>) -> 
ListViewChild {
+    let mut ranges = vec![];
+    let mut null_views = false;
+    let mut empty_end = 0;
+    for (valid, offset, size) in views {
+        if !valid {
+            null_views |= offset != 0 || size != 0;
+        } else if size == 0 {
+            empty_end = empty_end.max(offset);
+        } else {
+            ranges.push(offset..offset + size);
+        }
+    }
+    ranges.sort_unstable_by_key(|r| r.start);
+    let mut merged: Vec<Range<usize>> = vec![];
+    for r in ranges {
+        match merged.last_mut() {
+            Some(m) if r.start <= m.end => m.end = m.end.max(r.end),
+            _ => merged.push(r),
+        }
+    }
+    ListViewChild {
+        merged,
+        null_views,
+        empty_end,
+    }
+}
+
+/// List views can overlap, appear out of order and leave gaps in the child.
+///
+/// `minify` merges the child ranges of the valid views into disjoint ranges.
+/// It copies these ranges back to back into a new child, and moves each view
+/// by the size of the gaps before it. Overlapping views stay shared, and the
+/// gaps go away. If the valid views cover one range, `minify` slices the
+/// child to it instead of a copy.
+///
+/// Null rows and empty views get an offset and a size of zero.
+fn minify_list_view<O: OffsetSizeTrait>(
+    array: &GenericListViewArray<O>,
+    field: &FieldRef,
+) -> Result<ArrayRef, ArrowError> {
+    let nulls = minify_nulls(array.nulls());
+    let is_valid = |i: usize| nulls.as_ref().is_none_or(|n| n.is_valid(i));
+    let views = || {
+        array
+            .offsets()
+            .iter()
+            .zip(array.sizes())
+            .enumerate()
+            .map(|(i, (o, s))| (is_valid(i), o.as_usize(), s.as_usize()))
+    };
+
+    let ListViewChild {
+        merged,
+        null_views,
+        empty_end,
+    } = list_view_child(views());
+
+    // The offset in the new child of the first row of each merged range
+    let mut bases = Vec::with_capacity(merged.len());
+    let mut len = 0;
+    for r in &merged {
+        bases.push(len);
+        len += r.len();
+    }
+    let moved = |offset: usize| {
+        let i = merged.partition_point(|r| r.start <= offset) - 1;
+        bases[i] + offset - merged[i].start
+    };
+
+    let (offsets, sizes, values) = match merged.as_slice() {
+        [] | [_] => {
+            let range = merged.first().cloned().unwrap_or(0..0);
+            let values = minify_inner(&array.values().slice(range.start, 
range.len()))?;
+            if range.start == 0 && !null_views && empty_end <= range.end {
+                let offsets = minify_scalar_buffer(array.offsets());
+                let sizes = minify_scalar_buffer(array.sizes());
+                (offsets, sizes, values)
+            } else {
+                let (offsets, sizes) = views()
+                    .map(|(valid, offset, size)| match valid && size > 0 {
+                        true => (O::usize_as(offset - range.start), 
O::usize_as(size)),
+                        false => (O::zero(), O::zero()),
+                    })
+                    .unzip::<_, _, Vec<_>, Vec<_>>();
+                (offsets.into(), sizes.into(), values)
+            }
+        }
+        _ => {
+            let values = gather_ranges(array.values().as_ref(), &merged)?;
+            let (offsets, sizes) = views()
+                .map(|(valid, offset, size)| match valid && size > 0 {
+                    true => (O::usize_as(moved(offset)), O::usize_as(size)),
+                    false => (O::zero(), O::zero()),
+                })
+                .unzip::<_, _, Vec<_>, Vec<_>>();
+            (offsets.into(), sizes.into(), values)
+        }
+    };
+    // SAFETY: every view of a valid row lies inside `values`, and null rows
+    // have an offset and a size of zero
+    Ok(Arc::new(unsafe {
+        GenericListViewArray::<O>::new_unchecked(Arc::clone(field), offsets, 
sizes, values, nulls)
+    }))
+}
+
+/// Dense unions keep only the child rows that a row references, in order of
+/// ascending order. Rows that reference the same child row keep sharing it. 
Sparse unions slice every child to the union's rows.
+fn minify_union(
+    array: &UnionArray,
+    fields: &UnionFields,
+    mode: UnionMode,
+) -> Result<ArrayRef, ArrowError> {
+    let type_ids = minify_scalar_buffer(array.type_ids());
+    match mode {
+        // `UnionArray::slice` already slices the children of a sparse union
+        UnionMode::Sparse => {
+            let children = fields
+                .iter()
+                .map(|(type_id, _)| 
minify_inner(array.child(type_id).as_ref()))
+                .collect::<Result<Vec<_>, _>>()?;
+            // SAFETY: the type ids and the child rows they reference stay the 
same
+            Ok(Arc::new(unsafe {
+                UnionArray::new_unchecked(fields.clone(), type_ids, None, 
children)
+            }))
+        }
+        UnionMode::Dense => {
+            let old_offsets = array.offsets().expect("dense union has 
offsets");
+            let DenseUnionRows {
+                offsets,
+                mut indices,
+                in_order,
+            } = dense_union_rows(array, fields, 0..array.len());
+            if in_order
+                && fields
+                    .iter()
+                    .all(|(id, _)| indices[id as usize].len() == 
array.child(id).len())
+            {
+                let children = fields
+                    .iter()
+                    .map(|(type_id, _)| 
minify_inner(array.child(type_id).as_ref()))
+                    .collect::<Result<Vec<_>, _>>()?;
+                let offsets = Some(minify_scalar_buffer(old_offsets));
+                // SAFETY: the type ids, offsets and child rows stay the same
+                return Ok(Arc::new(unsafe {
+                    UnionArray::new_unchecked(fields.clone(), type_ids, 
offsets, children)
+                }));
+            }
+            let children = fields
+                .iter()
+                .map(|(type_id, _)| {
+                    let child = array.child(type_id).as_ref();
+                    // `take` copies shared rows of a nested dense union once
+                    // per row, and merges equal runs of a run-end encoded
+                    // array. `gather_ranges` does neither, so the result does
+                    // not depend on the values.
+                    let mut ranges = vec![];
+                    for i in std::mem::take(&mut indices[type_id as usize]) {
+                        push_range(&mut ranges, i as usize..i as usize + 1);
+                    }
+                    gather_ranges(child, &ranges)
+                })
+                .collect::<Result<Vec<_>, _>>()?;
+            let offsets = Some(ScalarBuffer::from(offsets));
+            // SAFETY: each offset indexes the child row that `gather_ranges` 
kept for it
+            Ok(Arc::new(unsafe {
+                UnionArray::new_unchecked(fields.clone(), type_ids, offsets, 
children)
+            }))
+        }
+    }
+}
+
+/// The child rows that a set of dense union rows references.
+struct DenseUnionRows {
+    /// The new offset of each row
+    offsets: Vec<i32>,
+    /// The referenced child rows of each type id, in ascending order
+    indices: Vec<Vec<u32>>,
+    /// `true` if every new offset equals the old offset
+    in_order: bool,
+}
+
+/// Numbers the child rows that `rows` of `array` reference in ascending
+/// order. Rows that share a child row keep sharing it.
+fn dense_union_rows(
+    array: &UnionArray,
+    fields: &UnionFields,
+    rows: impl Iterator<Item = usize> + Clone,
+) -> DenseUnionRows {
+    let type_ids = array.type_ids();
+    let old_offsets = array.offsets().expect("dense union has offsets");
+    // Type ids are in `0..128`, so a `Vec` can index them
+    let mut indices: Vec<Vec<u32>> = vec![Vec::new(); 128];
+    // The smallest and largest offset per type id. The lookup tables span
+    // only these offsets, so the cost depends on the rows and not on the
+    // child length.
+    let mut bounds = vec![(i32::MAX, -1); 128];
+    for i in rows.clone() {
+        let (min, max) = &mut bounds[type_ids[i] as usize];
+        *min = (*min).min(old_offsets[i]);
+        *max = (*max).max(old_offsets[i]);
+    }
+    // Maps each child row in the bounds to its new offset, or -1 if no row
+    // uses it yet
+    let mut new_offsets: Vec<Vec<i32>> = vec![Vec::new(); 128];
+    for (type_id, _) in fields.iter() {
+        let (min, max) = bounds[type_id as usize];
+        if max >= min {
+            new_offsets[type_id as usize] = vec![-1; (max - min) as usize + 1];
+        }
+    }
+    for i in rows.clone() {
+        let (type_id, offset) = (type_ids[i] as usize, old_offsets[i]);
+        new_offsets[type_id][(offset - bounds[type_id].0) as usize] = 0;
+    }
+    // Numbers the used child rows in ascending order. Gathered ranges then
+    // never go back, so a run-end encoded child copies each run value once.
+    for (type_id, _) in fields.iter() {
+        let (t, min) = (type_id as usize, bounds[type_id as usize].0);
+        for (j, new_offset) in new_offsets[t].iter_mut().enumerate() {
+            if *new_offset == 0 {
+                *new_offset = indices[t].len() as i32;
+                indices[t].push((min as usize + j) as u32);
+            }
+        }
+    }
+    let mut in_order = true;
+    let offsets = rows
+        .map(|i| {
+            let (type_id, offset) = (type_ids[i] as usize, old_offsets[i]);
+            let new_offset = new_offsets[type_id][(offset - bounds[type_id].0) 
as usize];
+            in_order &= new_offset == offset;
+            new_offset
+        })
+        .collect();
+    DenseUnionRows {
+        offsets,
+        indices,
+        in_order,
+    }
+}
+
+fn minify_dictionary<K: ArrowDictionaryKeyType>(
+    array: &DictionaryArray<K>,
+) -> Result<ArrayRef, ArrowError> {
+    let array = garbage_collect_values(array)?;
+    let keys = minify_primitive(array.keys());
+    let values = minify_inner(array.values().as_ref())?;
+    // SAFETY: `garbage_collect_dictionary` returns valid keys, and `minify`
+    // keeps the keys and the length of the values
+    Ok(Arc::new(unsafe {
+        DictionaryArray::<K>::new_unchecked(keys, values)
+    }))
+}
+
+/// Like [`garbage_collect_dictionary`], but copies the values with
+/// [`gather_ranges`]. `gather_ranges` keeps child rows that the values share,
+/// and does not merge equal runs of run-end encoded values as `take` does.

Review Comment:
   Two reasons. `garbage_collect_dictionary` does work proportional to the 
whole values array, which hurts for a small slice of a big dictionary. And its 
`filter` copies shared child rows once per reference for dense union / list 
view values, and re-splits run-end encoded ones, so the result can end up 
bigger than it needs to be.
   
   I think the right fix is to improve `garbage_collect_dictionary` itself and 
delete this one. It's private so we can do that any time, but it changes a 
public kernel's output so I'd rather do it as its own PR. Sound ok?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to