Skip to main content

vortex_arrow/
convert.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Canonical (non-plugin) conversions of Arrow arrays into Vortex arrays.
5//!
6//! Each `from_arrow_*` function converts one Arrow array shape; [`from_arrow_dyn`] dispatches on
7//! the Arrow [`DataType`]. These functions have no awareness of Arrow extension types — the
8//! plugin-aware entry points are the [`ArrowSession`](crate::ArrowSession) methods, which fall
9//! back to these conversions for non-extension data.
10
11use std::ops::Range;
12use std::sync::Arc;
13
14use arrow_array::AnyDictionaryArray;
15use arrow_array::Array as ArrowArray;
16use arrow_array::ArrowPrimitiveType;
17use arrow_array::BooleanArray as ArrowBooleanArray;
18use arrow_array::DictionaryArray;
19use arrow_array::FixedSizeListArray as ArrowFixedSizeListArray;
20use arrow_array::GenericByteArray;
21use arrow_array::GenericByteViewArray;
22use arrow_array::GenericListArray;
23use arrow_array::GenericListViewArray;
24use arrow_array::MapArray as ArrowMapArray;
25use arrow_array::NullArray as ArrowNullArray;
26use arrow_array::OffsetSizeTrait;
27use arrow_array::PrimitiveArray as ArrowPrimitiveArray;
28use arrow_array::RecordBatch;
29use arrow_array::StructArray as ArrowStructArray;
30use arrow_array::cast::AsArray;
31use arrow_array::cast::as_null_array;
32use arrow_array::make_array;
33use arrow_array::types::ArrowDictionaryKeyType;
34use arrow_array::types::ByteArrayType;
35use arrow_array::types::ByteViewType;
36use arrow_array::types::Date32Type;
37use arrow_array::types::Date64Type;
38use arrow_array::types::Decimal32Type;
39use arrow_array::types::Decimal64Type;
40use arrow_array::types::Decimal128Type;
41use arrow_array::types::Decimal256Type;
42use arrow_array::types::Float16Type;
43use arrow_array::types::Float32Type;
44use arrow_array::types::Float64Type;
45use arrow_array::types::Int8Type;
46use arrow_array::types::Int16Type;
47use arrow_array::types::Int32Type;
48use arrow_array::types::Int64Type;
49use arrow_array::types::Time32MillisecondType;
50use arrow_array::types::Time32SecondType;
51use arrow_array::types::Time64MicrosecondType;
52use arrow_array::types::Time64NanosecondType;
53use arrow_array::types::TimestampMicrosecondType;
54use arrow_array::types::TimestampMillisecondType;
55use arrow_array::types::TimestampNanosecondType;
56use arrow_array::types::TimestampSecondType;
57use arrow_array::types::UInt8Type;
58use arrow_array::types::UInt16Type;
59use arrow_array::types::UInt32Type;
60use arrow_array::types::UInt64Type;
61use arrow_buffer::ArrowNativeType;
62use arrow_buffer::BooleanBuffer;
63use arrow_buffer::Buffer as ArrowBuffer;
64use arrow_buffer::ScalarBuffer;
65use arrow_buffer::buffer::NullBuffer;
66use arrow_buffer::buffer::OffsetBuffer;
67use arrow_schema::DataType;
68use arrow_schema::TimeUnit as ArrowTimeUnit;
69use vortex_array::ArrayRef;
70use vortex_array::IntoArray;
71use vortex_array::arrays::BoolArray;
72use vortex_array::arrays::DecimalArray;
73use vortex_array::arrays::DictArray;
74use vortex_array::arrays::ExtensionArray;
75use vortex_array::arrays::FixedSizeListArray;
76use vortex_array::arrays::ListArray;
77use vortex_array::arrays::ListViewArray;
78use vortex_array::arrays::MapArray;
79use vortex_array::arrays::NullArray;
80use vortex_array::arrays::PrimitiveArray;
81use vortex_array::arrays::Struct;
82use vortex_array::arrays::StructArray;
83use vortex_array::arrays::TemporalArray;
84use vortex_array::arrays::VarBinArray;
85use vortex_array::arrays::VarBinViewArray;
86use vortex_array::arrays::decimal::check_precision;
87use vortex_array::arrays::decimal::copy_to_canonical_width;
88use vortex_array::arrays::struct_::StructArrayExt;
89use vortex_array::buffer::BufferHandle;
90use vortex_array::dtype::DType;
91use vortex_array::dtype::DecimalDType;
92use vortex_array::dtype::FieldNames;
93use vortex_array::dtype::IntegerPType;
94use vortex_array::dtype::MapDType;
95use vortex_array::dtype::NativeDecimalType;
96use vortex_array::dtype::NativePType;
97use vortex_array::dtype::Nullability;
98use vortex_array::dtype::PType;
99use vortex_array::dtype::i256;
100use vortex_array::extension::datetime::TimeUnit;
101use vortex_array::extension::datetime::Timestamp;
102use vortex_array::validity::Validity;
103use vortex_buffer::Alignment;
104use vortex_buffer::BitBuffer;
105use vortex_buffer::Buffer;
106use vortex_buffer::ByteBuffer;
107use vortex_error::VortexResult;
108use vortex_error::vortex_bail;
109use vortex_error::vortex_ensure;
110use vortex_error::vortex_ensure_eq;
111use vortex_error::vortex_err;
112use vortex_error::vortex_panic;
113use vortex_mask::Mask;
114
115use crate::dtype::from_arrow_time_unit;
116
117/// Zero-copy conversion of Arrow buffers into non-nullable Vortex arrays.
118///
119/// This mirrors [`IntoArray`] for Arrow buffer types; a separate trait is required because both
120/// [`IntoArray`] and the Arrow buffer types are foreign to this crate.
121pub trait IntoVortexArray {
122    /// Convert this Arrow buffer into a non-nullable Vortex array without copying.
123    fn into_array(self) -> ArrayRef;
124}
125
126impl IntoVortexArray for ArrowBuffer {
127    fn into_array(self) -> ArrayRef {
128        PrimitiveArray::from_byte_buffer(
129            ByteBuffer::from_arrow_buffer(self, Alignment::of::<u8>()),
130            PType::U8,
131            Validity::NonNullable,
132        )
133        .into_array()
134    }
135}
136
137impl IntoVortexArray for BooleanBuffer {
138    fn into_array(self) -> ArrayRef {
139        BoolArray::new(self.into(), Validity::NonNullable).into_array()
140    }
141}
142
143impl<T> IntoVortexArray for ScalarBuffer<T>
144where
145    T: ArrowNativeType + NativePType,
146{
147    fn into_array(self) -> ArrayRef {
148        PrimitiveArray::new(
149            Buffer::<T>::from_arrow_scalar_buffer(self),
150            Validity::NonNullable,
151        )
152        .into_array()
153    }
154}
155
156impl<O> IntoVortexArray for OffsetBuffer<O>
157where
158    O: IntegerPType + OffsetSizeTrait,
159{
160    fn into_array(self) -> ArrayRef {
161        let primitive = PrimitiveArray::new(
162            Buffer::from_arrow_scalar_buffer(self.into_inner()),
163            Validity::NonNullable,
164        );
165
166        primitive.into_array()
167    }
168}
169
170/// Zero-copy conversion of an Arrow numeric primitive array into a Vortex array.
171///
172/// Use [`from_arrow_temporal`] for Arrow temporal arrays, which carry a logical dtype beyond
173/// their physical primitive storage.
174pub fn from_arrow_primitive<T: ArrowPrimitiveType>(
175    value: &ArrowPrimitiveArray<T>,
176    nullable: bool,
177) -> VortexResult<ArrayRef>
178where
179    T::Native: NativePType,
180{
181    let buffer = Buffer::from_arrow_scalar_buffer(value.values().clone());
182    let validity = nulls(value.nulls(), nullable)?;
183    Ok(PrimitiveArray::new(buffer, validity).into_array())
184}
185
186/// Conversion of an Arrow `Decimal32` array into a Vortex decimal array, zero-copy when the Arrow
187/// width is the [canonical width](DecimalDType::canonical_values_type), otherwise a checked copy.
188pub fn from_arrow_decimal32(
189    array: &ArrowPrimitiveArray<Decimal32Type>,
190    nullable: bool,
191) -> VortexResult<ArrayRef> {
192    let values = Buffer::from_arrow_scalar_buffer(array.values().clone());
193    from_arrow_decimal(
194        values,
195        array.nulls(),
196        array.precision(),
197        array.scale(),
198        nullable,
199    )
200}
201
202/// Conversion of an Arrow `Decimal64` array into a Vortex decimal array, zero-copy when the Arrow
203/// width is the [canonical width](DecimalDType::canonical_values_type), otherwise a checked copy.
204pub fn from_arrow_decimal64(
205    array: &ArrowPrimitiveArray<Decimal64Type>,
206    nullable: bool,
207) -> VortexResult<ArrayRef> {
208    let values = Buffer::from_arrow_scalar_buffer(array.values().clone());
209    from_arrow_decimal(
210        values,
211        array.nulls(),
212        array.precision(),
213        array.scale(),
214        nullable,
215    )
216}
217
218/// Conversion of an Arrow `Decimal128` array into a Vortex decimal array, zero-copy when the Arrow
219/// width is the [canonical width](DecimalDType::canonical_values_type), otherwise a checked copy.
220pub fn from_arrow_decimal128(
221    array: &ArrowPrimitiveArray<Decimal128Type>,
222    nullable: bool,
223) -> VortexResult<ArrayRef> {
224    let values = Buffer::from_arrow_scalar_buffer(array.values().clone());
225    from_arrow_decimal(
226        values,
227        array.nulls(),
228        array.precision(),
229        array.scale(),
230        nullable,
231    )
232}
233
234/// Conversion of an Arrow `Decimal256` array into a Vortex decimal array, zero-copy when the Arrow
235/// width is the [canonical width](DecimalDType::canonical_values_type), otherwise a checked copy.
236pub fn from_arrow_decimal256(
237    array: &ArrowPrimitiveArray<Decimal256Type>,
238    nullable: bool,
239) -> VortexResult<ArrayRef> {
240    let values = Buffer::from_arrow_scalar_buffer(array.values().clone());
241    // SAFETY: Our i256 implementation has the same bit-pattern representation of the
242    //  arrow_buffer::i256 type. It is safe to treat values held inside the buffer as values
243    //  of either type.
244    let values = unsafe { std::mem::transmute::<Buffer<arrow_buffer::i256>, Buffer<i256>>(values) };
245    from_arrow_decimal(
246        values,
247        array.nulls(),
248        array.precision(),
249        array.scale(),
250        nullable,
251    )
252}
253
254/// Converts the values of an Arrow decimal array into a Vortex decimal array at the canonical width
255/// of its precision.
256///
257/// arrow-rs does not check that the values of an array fit its precision, so this function checks
258/// every valid value. When `T` is the canonical width, the array keeps the Arrow buffer and
259/// [`check_precision`] checks it. Otherwise [`copy_to_canonical_width`] copies the values, which
260/// writes zeros into the null slots when it narrows. Null slots are never checked.
261///
262/// # Errors
263///
264/// Returns an error if the precision or scale is invalid, if `nullable` is false and the array has
265/// nulls, or if a valid value is outside the precision.
266fn from_arrow_decimal<T: NativeDecimalType>(
267    values: Buffer<T>,
268    arrow_nulls: Option<&NullBuffer>,
269    precision: u8,
270    scale: i8,
271    nullable: bool,
272) -> VortexResult<ArrayRef> {
273    let decimal_dtype = DecimalDType::try_new(precision, scale)?;
274    let validity = nulls(arrow_nulls, nullable)?;
275    let mask = arrow_nulls.map_or_else(
276        || Mask::new_true(values.len()),
277        |arrow_nulls| Mask::from_buffer(BitBuffer::from(arrow_nulls.inner().clone())),
278    );
279
280    let values_type = decimal_dtype.canonical_values_type();
281    let checked_values = if T::DECIMAL_TYPE == values_type {
282        check_precision(values.as_slice(), &mask, decimal_dtype)
283            .map(|()| BufferHandle::new_host(values.into_byte_buffer()))
284    } else {
285        copy_to_canonical_width(values.as_slice(), &mask, decimal_dtype)
286    };
287    let checked_values = checked_values.map_err(|err| {
288        err.with_context(format!(
289            "Arrow decimal import requires every valid value to be within the precision of \
290             {decimal_dtype}; call arrow-rs PrimitiveArray::null_if_overflow_precision before \
291             the import to turn such values into nulls"
292        ))
293    })?;
294
295    // SAFETY: Every valid value is within the precision of `decimal_dtype`. `check_precision`
296    // checked the zero-copy values, and `copy_to_canonical_width` checks a narrowing copy. A
297    // widening copy needs no check: the canonical width is wider than `T` only when the precision
298    // is above `T::MAX_PRECISION`, and every value of `T` has at most `T::MAX_PRECISION + 1`
299    // digits. Arrow keeps its null buffer at the length of the values, so the validity matches.
300    let array = unsafe {
301        DecimalArray::new_unchecked_handle(checked_values, values_type, decimal_dtype, validity)
302    };
303
304    Ok(array.into_array())
305}
306
307/// Conversion of an Arrow temporal array (timestamp/date/time) into a Vortex temporal
308/// extension array.
309pub fn from_arrow_temporal<T: ArrowPrimitiveType>(
310    value: &ArrowPrimitiveArray<T>,
311    nullable: bool,
312) -> VortexResult<ArrayRef>
313where
314    T::Native: NativePType,
315{
316    let arr = PrimitiveArray::new(
317        Buffer::from_arrow_scalar_buffer(value.values().clone()),
318        nulls(value.nulls(), nullable)?,
319    )
320    .into_array();
321
322    Ok(match value.data_type() {
323        DataType::Timestamp(time_unit, tz) => {
324            let dtype = Timestamp::try_new_with_tz(
325                from_arrow_time_unit(*time_unit),
326                tz.clone(),
327                arr.dtype().nullability(),
328            )?;
329            ExtensionArray::try_new(dtype.erased(), arr)?.into_array()
330        }
331        DataType::Time32(time_unit) => {
332            TemporalArray::new_time(arr, from_arrow_time_unit(*time_unit)).into()
333        }
334        DataType::Time64(time_unit) => {
335            TemporalArray::new_time(arr, from_arrow_time_unit(*time_unit)).into()
336        }
337        DataType::Date32 => TemporalArray::new_date(arr, TimeUnit::Days).into(),
338        DataType::Date64 => TemporalArray::new_date(arr, TimeUnit::Milliseconds).into(),
339        DataType::Duration(_) | DataType::Interval(_) => {
340            vortex_bail!("Arrow {} arrays are not supported", value.data_type())
341        }
342        _ => vortex_panic!("Invalid temporal type: {}", value.data_type()),
343    })
344}
345
346/// Rebase a (possibly sliced) Arrow offset buffer to start at zero.
347///
348/// A sliced Arrow string, binary or list array keeps its parent's whole child,
349/// so the returned range selects just the child data its rows reference.
350pub(crate) fn trim_offsets<O: OffsetSizeTrait>(
351    offsets: &OffsetBuffer<O>,
352) -> (OffsetBuffer<O>, Range<usize>) {
353    let first = offsets[0];
354    let referenced = first.as_usize()..offsets[offsets.len() - 1].as_usize();
355    if first.as_usize() == 0 {
356        return (offsets.clone(), referenced);
357    }
358    let rebased = OffsetBuffer::new(offsets.iter().map(|&offset| offset - first).collect());
359    (rebased, referenced)
360}
361
362/// Conversion of an Arrow (large) string/binary array into a Vortex `VarBin` array, sharing its
363/// bytes.
364pub fn from_arrow_bytes<T: ByteArrayType>(
365    value: &GenericByteArray<T>,
366    nullable: bool,
367) -> VortexResult<ArrayRef>
368where
369    <T as ByteArrayType>::Offset: IntegerPType,
370{
371    let dtype = match T::DATA_TYPE {
372        DataType::Binary | DataType::LargeBinary => DType::Binary(nullable.into()),
373        DataType::Utf8 | DataType::LargeUtf8 => DType::Utf8(nullable.into()),
374        dt => vortex_panic!("Invalid data type for ByteArray: {dt}"),
375    };
376    let (offsets, referenced) = trim_offsets(value.offsets());
377    let bytes = value
378        .values()
379        .slice_with_length(referenced.start, referenced.len());
380    // SAFETY: Arrow arrays are already validated (valid UTF-8, valid offsets, correct validity).
381    Ok(unsafe {
382        VarBinArray::new_unchecked(
383            offsets.into_array(),
384            ByteBuffer::from_arrow_buffer(bytes, Alignment::of::<u8>()),
385            dtype,
386            nulls(value.nulls(), nullable)?,
387        )
388    }
389    .into_array())
390}
391
392/// Zero-copy conversion of an Arrow string/binary view array into a Vortex `VarBinView` array.
393pub fn from_arrow_byte_view<T: ByteViewType>(
394    value: &GenericByteViewArray<T>,
395    nullable: bool,
396) -> VortexResult<ArrayRef> {
397    let dtype = match T::DATA_TYPE {
398        DataType::BinaryView => DType::Binary(nullable.into()),
399        DataType::Utf8View => DType::Utf8(nullable.into()),
400        dt => vortex_panic!("Invalid data type for ByteViewArray: {dt}"),
401    };
402
403    let views_buffer = Buffer::from_byte_buffer(
404        Buffer::from_arrow_scalar_buffer(value.views().clone()).into_byte_buffer(),
405    );
406
407    // SAFETY: arrow-rs ByteViewArray already checks the same invariants, we inherit those
408    //  guarantees by zero-copy constructing from one.
409    Ok(unsafe {
410        VarBinViewArray::new_unchecked(
411            views_buffer,
412            Arc::from(
413                value
414                    .data_buffers()
415                    .iter()
416                    .map(|b| ByteBuffer::from_arrow_buffer(b.clone(), Alignment::of::<u8>()))
417                    .collect::<Vec<_>>(),
418            ),
419            dtype,
420            nulls(value.nulls(), nullable)?,
421        )
422        .into_array()
423    })
424}
425
426/// Zero-copy conversion of an Arrow boolean array into a Vortex `Bool` array.
427pub fn from_arrow_boolean(value: &ArrowBooleanArray, nullable: bool) -> VortexResult<ArrayRef> {
428    Ok(BoolArray::new(
429        value.values().clone().into(),
430        nulls(value.nulls(), nullable)?,
431    )
432    .into_array())
433}
434
435/// Strip out the nulls from this array and return a new array without nulls.
436pub(crate) fn remove_nulls(data: arrow_data::ArrayData) -> VortexResult<arrow_data::ArrayData> {
437    if data.null_count() == 0 {
438        // No nulls to remove, return the array as is
439        return Ok(data);
440    }
441
442    let children = match data.data_type() {
443        DataType::Struct(fields) => Some(
444            fields
445                .iter()
446                .zip(data.child_data().iter())
447                .map(|(field, child_data)| {
448                    if field.is_nullable() {
449                        Ok(child_data.clone())
450                    } else {
451                        remove_nulls(child_data.clone())
452                    }
453                })
454                .collect::<VortexResult<Vec<_>>>()?,
455        ),
456        DataType::List(f)
457        | DataType::LargeList(f)
458        | DataType::ListView(f)
459        | DataType::LargeListView(f)
460        | DataType::FixedSizeList(f, _)
461            if !f.is_nullable() =>
462        {
463            // All list types only have one child
464            vortex_ensure_eq!(
465                data.child_data().len(),
466                1,
467                "List types should have one child"
468            );
469            Some(vec![remove_nulls(data.child_data()[0].clone())?])
470        }
471        _ => None,
472    };
473
474    let mut builder = data.into_builder().nulls(None);
475    if let Some(children) = children {
476        builder = builder.child_data(children);
477    }
478    builder
479        .build()
480        .map_err(|e| vortex_err!("Failed to reconstruct Arrow array without nulls: {e}"))
481}
482
483/// Conversion of an Arrow struct array into a Vortex `Struct` array, converting each column.
484pub fn from_arrow_struct(value: &ArrowStructArray, nullable: bool) -> VortexResult<ArrayRef> {
485    Ok(StructArray::try_new(
486        value.column_names().iter().copied().collect(),
487        value
488            .columns()
489            .iter()
490            .zip(value.fields())
491            .map(|(c, field)| {
492                // Arrow pushes down nulls, even into non-nullable fields. So we strip them
493                // out here because Vortex is a little more strict.
494                if c.null_count() > 0 && !field.is_nullable() {
495                    let stripped = make_array(remove_nulls(c.into_data())?);
496                    from_arrow_dyn(stripped.as_ref(), false)
497                } else {
498                    from_arrow_dyn(c.as_ref(), field.is_nullable())
499                }
500            })
501            .collect::<VortexResult<Vec<_>>>()?,
502        value.len(),
503        nulls(value.nulls(), nullable)?,
504    )?
505    .into_array())
506}
507
508/// Conversion of an Arrow (large) list array into a Vortex `List` array.
509pub fn from_arrow_list<O: IntegerPType + OffsetSizeTrait>(
510    value: &GenericListArray<O>,
511    nullable: bool,
512) -> VortexResult<ArrayRef> {
513    // Extract the validity of the underlying element array.
514    let elements_are_nullable = match value.data_type() {
515        DataType::List(field) => field.is_nullable(),
516        DataType::LargeList(field) => field.is_nullable(),
517        dt => vortex_panic!("Invalid data type for ListArray: {dt}"),
518    };
519
520    let (offsets, referenced) = trim_offsets(value.offsets());
521    let elements = from_arrow_dyn(
522        value
523            .values()
524            .slice(referenced.start, referenced.len())
525            .as_ref(),
526        elements_are_nullable,
527    )?;
528    let nulls = nulls(value.nulls(), nullable)?;
529
530    // SAFETY: Arrow offsets are non-negative and sorted, and `trim_offsets` rebases them onto
531    // the referenced values, so the last offset is the elements length. The validity comes from
532    // the same Arrow array, so it has one entry per list.
533    Ok(unsafe { ListArray::new_unchecked(elements, offsets.into_array(), nulls) }.into_array())
534}
535
536/// Conversion of an Arrow (large) list-view array into a Vortex `ListView` array.
537pub fn from_arrow_list_view<O: OffsetSizeTrait + NativePType>(
538    array: &GenericListViewArray<O>,
539    nullable: bool,
540) -> VortexResult<ArrayRef> {
541    // Extract the validity of the underlying element array.
542    let elements_are_nullable = match array.data_type() {
543        DataType::ListView(field) => field.is_nullable(),
544        DataType::LargeListView(field) => field.is_nullable(),
545        dt => vortex_panic!("Invalid data type for ListViewArray: {dt}"),
546    };
547
548    let elements = from_arrow_dyn(array.values().as_ref(), elements_are_nullable)?;
549
550    // `offsets` and `sizes` are always non-nullable.
551    let offsets = array.offsets().clone().into_array();
552    let sizes = array.sizes().clone().into_array();
553    let nulls = nulls(array.nulls(), nullable)?;
554
555    // SAFETY: Arrow list views share one integer type for offsets and sizes, and every view
556    // lies within the values. The validity comes from the same Arrow array.
557    Ok(unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, nulls) }.into_array())
558}
559
560/// Conversion of an Arrow fixed-size list array into a Vortex `FixedSizeList` array.
561pub fn from_arrow_fixed_size_list(
562    array: &ArrowFixedSizeListArray,
563    nullable: bool,
564) -> VortexResult<ArrayRef> {
565    let DataType::FixedSizeList(field, list_size) = array.data_type() else {
566        vortex_panic!("Invalid data type for ListArray: {}", array.data_type());
567    };
568
569    Ok(FixedSizeListArray::try_new(
570        from_arrow_dyn(array.values().as_ref(), field.is_nullable())?,
571        *list_size as u32,
572        nulls(array.nulls(), nullable)?,
573        array.len(),
574    )?
575    .into_array())
576}
577
578pub(crate) fn map_from_arrow_parts(
579    entries: ArrayRef,
580    offsets: &OffsetBuffer<i32>,
581    arrow_nulls: Option<&NullBuffer>,
582    keys_sorted: bool,
583    nullable: bool,
584) -> VortexResult<ArrayRef> {
585    let DType::Struct(struct_dtype, Nullability::NonNullable) = entries.dtype() else {
586        vortex_bail!(
587            "Arrow map entries must import as non-nullable struct, got {}",
588            entries.dtype()
589        );
590    };
591    vortex_ensure_eq!(
592        struct_dtype.nfields(),
593        2,
594        "Arrow map entries struct must contain exactly two fields"
595    );
596
597    let key_dtype = struct_dtype
598        .field_by_index(0)
599        .ok_or_else(|| vortex_err!("Arrow map entries struct missing key field"))?;
600    vortex_ensure!(
601        !key_dtype.is_nullable(),
602        "Arrow map key field must be non-nullable"
603    );
604    let value_dtype = struct_dtype
605        .field_by_index(1)
606        .ok_or_else(|| vortex_err!("Arrow map entries struct missing value field"))?;
607    let map_dtype = MapDType::try_new(key_dtype, value_dtype, keys_sorted)?;
608    let entries_struct = entries.as_::<Struct>();
609    let entries = StructArray::try_new(
610        FieldNames::from(["key", "value"]),
611        vec![
612            entries_struct.unmasked_field(0).clone(),
613            entries_struct.unmasked_field(1).clone(),
614        ],
615        entries.len(),
616        Validity::NonNullable,
617    )?
618    .into_array();
619
620    let len = offsets.len() - 1;
621    let sizes = Buffer::<i32>::from_iter(offsets.windows(2).map(|window| window[1] - window[0]))
622        .into_array();
623    let offsets = offsets.inner().slice(0, len).into_array();
624    let validity = nulls(arrow_nulls, nullable)?;
625    // SAFETY: the sizes are the differences of sorted, non-negative Arrow Map offsets that lie
626    // within the entries, and share their integer type. The validity has one entry per map.
627    let entries = unsafe { ListViewArray::new_unchecked(entries, offsets, sizes, validity) };
628    // SAFETY: Arrow Map offsets are sorted list offsets. Vortex sizes are adjacent offset
629    // differences, so every view's end equals the next view's start. The caller trims the
630    // entries to the referenced range and rebases the offsets, so the first offset is zero and
631    // the last offset equals the entry count.
632    let entries = unsafe { entries.with_zero_copy_to_list(true) };
633
634    Ok(MapArray::try_new(map_dtype, entries)?.into_array())
635}
636
637/// Select the child entries that the map offsets reference, and rebase the offsets.
638pub(crate) fn trim_map_entries(array: &ArrowMapArray) -> (ArrowStructArray, OffsetBuffer<i32>) {
639    let (offsets, referenced) = trim_offsets(array.offsets());
640    let entries = array.entries().slice(referenced.start, referenced.len());
641
642    (entries, offsets)
643}
644
645/// Conversion of an Arrow map array into a Vortex `Map` array.
646pub fn from_arrow_map(array: &ArrowMapArray, nullable: bool) -> VortexResult<ArrayRef> {
647    let DataType::Map(_, keys_sorted) = array.data_type() else {
648        vortex_panic!("Invalid data type for MapArray: {}", array.data_type());
649    };
650    let (entries, offsets) = trim_map_entries(array);
651    let entries = from_arrow_struct(&entries, false)?;
652    map_from_arrow_parts(entries, &offsets, array.nulls(), *keys_sorted, nullable)
653}
654
655/// Conversion of an Arrow null array into a Vortex `Null` array.
656pub fn from_arrow_null(value: &ArrowNullArray, nullable: bool) -> VortexResult<ArrayRef> {
657    vortex_ensure!(
658        nullable,
659        "Cannot convert an Arrow NullArray into a non-nullable Vortex array"
660    );
661    Ok(NullArray::new(value.len()).into_array())
662}
663
664/// Conversion of an Arrow dictionary array into a Vortex `Dict` array.
665pub fn from_arrow_dictionary<K: ArrowDictionaryKeyType>(
666    array: &DictionaryArray<K>,
667    nullable: bool,
668) -> VortexResult<DictArray> {
669    let keys = AnyDictionaryArray::keys(array);
670    let keys = from_arrow_dyn(keys, keys.is_nullable())?;
671    let values = from_arrow_dyn(array.values().as_ref(), nullable)?;
672    // SAFETY: we assume that Arrow has checked the invariants on construction.
673    Ok(unsafe { DictArray::new_unchecked(keys, values) })
674}
675
676/// Convert an Arrow [`NullBuffer`] into a Vortex [`Validity`] for an array of the given
677/// nullability.
678///
679/// # Errors
680///
681/// Returns an error if `nullable` is false but the null buffer contains nulls.
682pub fn nulls(nulls: Option<&NullBuffer>, nullable: bool) -> VortexResult<Validity> {
683    if nullable {
684        Ok(nulls
685            .map(|nulls| {
686                if nulls.is_empty() {
687                    Validity::AllValid
688                } else if nulls.null_count() == nulls.len() {
689                    Validity::AllInvalid
690                } else {
691                    Validity::from(BitBuffer::from(nulls.inner().clone()))
692                }
693            })
694            .unwrap_or(Validity::AllValid))
695    } else {
696        let null_count = nulls.map(NullBuffer::null_count).unwrap_or(0);
697        vortex_ensure_eq!(
698            null_count,
699            0,
700            "Cannot convert an Arrow array containing nulls into a non-nullable Vortex array"
701        );
702        Ok(Validity::NonNullable)
703    }
704}
705
706/// Canonical conversion of any supported Arrow array into a Vortex array, dispatching on the
707/// Arrow [`DataType`].
708pub fn from_arrow_dyn(array: &dyn ArrowArray, nullable: bool) -> VortexResult<ArrayRef> {
709    match array.data_type() {
710        DataType::Boolean => from_arrow_boolean(array.as_boolean(), nullable),
711        DataType::UInt8 => from_arrow_primitive(array.as_primitive::<UInt8Type>(), nullable),
712        DataType::UInt16 => from_arrow_primitive(array.as_primitive::<UInt16Type>(), nullable),
713        DataType::UInt32 => from_arrow_primitive(array.as_primitive::<UInt32Type>(), nullable),
714        DataType::UInt64 => from_arrow_primitive(array.as_primitive::<UInt64Type>(), nullable),
715        DataType::Int8 => from_arrow_primitive(array.as_primitive::<Int8Type>(), nullable),
716        DataType::Int16 => from_arrow_primitive(array.as_primitive::<Int16Type>(), nullable),
717        DataType::Int32 => from_arrow_primitive(array.as_primitive::<Int32Type>(), nullable),
718        DataType::Int64 => from_arrow_primitive(array.as_primitive::<Int64Type>(), nullable),
719        DataType::Float16 => from_arrow_primitive(array.as_primitive::<Float16Type>(), nullable),
720        DataType::Float32 => from_arrow_primitive(array.as_primitive::<Float32Type>(), nullable),
721        DataType::Float64 => from_arrow_primitive(array.as_primitive::<Float64Type>(), nullable),
722        DataType::Utf8 => from_arrow_bytes(array.as_string::<i32>(), nullable),
723        DataType::LargeUtf8 => from_arrow_bytes(array.as_string::<i64>(), nullable),
724        DataType::Binary => from_arrow_bytes(array.as_binary::<i32>(), nullable),
725        DataType::LargeBinary => from_arrow_bytes(array.as_binary::<i64>(), nullable),
726        DataType::BinaryView => from_arrow_byte_view(array.as_binary_view(), nullable),
727        DataType::Utf8View => from_arrow_byte_view(array.as_string_view(), nullable),
728        DataType::Struct(_) => from_arrow_struct(array.as_struct(), nullable),
729        DataType::List(_) => from_arrow_list(array.as_list::<i32>(), nullable),
730        DataType::LargeList(_) => from_arrow_list(array.as_list::<i64>(), nullable),
731        DataType::ListView(_) => from_arrow_list_view(array.as_list_view::<i32>(), nullable),
732        DataType::LargeListView(_) => from_arrow_list_view(array.as_list_view::<i64>(), nullable),
733        DataType::FixedSizeList(..) => {
734            from_arrow_fixed_size_list(array.as_fixed_size_list(), nullable)
735        }
736        DataType::Map(..) => from_arrow_map(array.as_map(), nullable),
737        DataType::Null => from_arrow_null(as_null_array(array), nullable),
738        DataType::Timestamp(u, _) => match u {
739            ArrowTimeUnit::Second => {
740                from_arrow_temporal(array.as_primitive::<TimestampSecondType>(), nullable)
741            }
742            ArrowTimeUnit::Millisecond => {
743                from_arrow_temporal(array.as_primitive::<TimestampMillisecondType>(), nullable)
744            }
745            ArrowTimeUnit::Microsecond => {
746                from_arrow_temporal(array.as_primitive::<TimestampMicrosecondType>(), nullable)
747            }
748            ArrowTimeUnit::Nanosecond => {
749                from_arrow_temporal(array.as_primitive::<TimestampNanosecondType>(), nullable)
750            }
751        },
752        DataType::Date32 => from_arrow_temporal(array.as_primitive::<Date32Type>(), nullable),
753        DataType::Date64 => from_arrow_temporal(array.as_primitive::<Date64Type>(), nullable),
754        DataType::Time32(u) => match u {
755            ArrowTimeUnit::Second => {
756                from_arrow_temporal(array.as_primitive::<Time32SecondType>(), nullable)
757            }
758            ArrowTimeUnit::Millisecond => {
759                from_arrow_temporal(array.as_primitive::<Time32MillisecondType>(), nullable)
760            }
761            ArrowTimeUnit::Microsecond | ArrowTimeUnit::Nanosecond => unreachable!(),
762        },
763        DataType::Time64(u) => match u {
764            ArrowTimeUnit::Microsecond => {
765                from_arrow_temporal(array.as_primitive::<Time64MicrosecondType>(), nullable)
766            }
767            ArrowTimeUnit::Nanosecond => {
768                from_arrow_temporal(array.as_primitive::<Time64NanosecondType>(), nullable)
769            }
770            ArrowTimeUnit::Second | ArrowTimeUnit::Millisecond => unreachable!(),
771        },
772        DataType::Decimal32(..) => {
773            from_arrow_decimal32(array.as_primitive::<Decimal32Type>(), nullable)
774        }
775        DataType::Decimal64(..) => {
776            from_arrow_decimal64(array.as_primitive::<Decimal64Type>(), nullable)
777        }
778        DataType::Decimal128(..) => {
779            from_arrow_decimal128(array.as_primitive::<Decimal128Type>(), nullable)
780        }
781        DataType::Decimal256(..) => {
782            from_arrow_decimal256(array.as_primitive::<Decimal256Type>(), nullable)
783        }
784        DataType::Dictionary(key_type, _) => match key_type.as_ref() {
785            DataType::Int8 => Ok(from_arrow_dictionary(
786                array.as_dictionary::<Int8Type>(),
787                nullable,
788            )?
789            .into_array()),
790            DataType::Int16 => Ok(from_arrow_dictionary(
791                array.as_dictionary::<Int16Type>(),
792                nullable,
793            )?
794            .into_array()),
795            DataType::Int32 => Ok(from_arrow_dictionary(
796                array.as_dictionary::<Int32Type>(),
797                nullable,
798            )?
799            .into_array()),
800            DataType::Int64 => Ok(from_arrow_dictionary(
801                array.as_dictionary::<Int64Type>(),
802                nullable,
803            )?
804            .into_array()),
805            DataType::UInt8 => Ok(from_arrow_dictionary(
806                array.as_dictionary::<UInt8Type>(),
807                nullable,
808            )?
809            .into_array()),
810            DataType::UInt16 => Ok(from_arrow_dictionary(
811                array.as_dictionary::<UInt16Type>(),
812                nullable,
813            )?
814            .into_array()),
815            DataType::UInt32 => Ok(from_arrow_dictionary(
816                array.as_dictionary::<UInt32Type>(),
817                nullable,
818            )?
819            .into_array()),
820            DataType::UInt64 => Ok(from_arrow_dictionary(
821                array.as_dictionary::<UInt64Type>(),
822                nullable,
823            )?
824            .into_array()),
825            key_dt => vortex_bail!("Unsupported dictionary key type: {key_dt}"),
826        },
827        dt => {
828            vortex_bail!("Array encoding not implemented for Arrow data type {dt}")
829        }
830    }
831}
832
833/// Canonical conversion of an Arrow [`RecordBatch`] into a Vortex struct array.
834pub fn from_arrow_batch(batch: &RecordBatch, nullable: bool) -> VortexResult<ArrayRef> {
835    from_arrow_struct(&arrow_array::StructArray::from(batch.clone()), nullable)
836}
837
838#[cfg(test)]
839mod tests {
840    use std::ops::Range;
841    use std::sync::Arc;
842    use std::sync::LazyLock;
843
844    use arrow_array::Array as ArrowArray;
845    use arrow_array::BinaryArray;
846    use arrow_array::BooleanArray;
847    use arrow_array::Date32Array;
848    use arrow_array::Date64Array;
849    use arrow_array::Decimal128Array;
850    use arrow_array::Decimal256Array;
851    use arrow_array::FixedSizeListArray as ArrowFixedSizeListArray;
852    use arrow_array::Float32Array;
853    use arrow_array::Float64Array;
854    use arrow_array::GenericListViewArray;
855    use arrow_array::Int8Array;
856    use arrow_array::Int16Array;
857    use arrow_array::Int32Array;
858    use arrow_array::Int64Array;
859    use arrow_array::LargeBinaryArray;
860    use arrow_array::LargeStringArray;
861    use arrow_array::NullArray;
862    use arrow_array::RecordBatch;
863    use arrow_array::StringArray;
864    use arrow_array::StructArray;
865    use arrow_array::Time32MillisecondArray;
866    use arrow_array::Time32SecondArray;
867    use arrow_array::Time64MicrosecondArray;
868    use arrow_array::Time64NanosecondArray;
869    use arrow_array::TimestampMicrosecondArray;
870    use arrow_array::TimestampMillisecondArray;
871    use arrow_array::TimestampNanosecondArray;
872    use arrow_array::TimestampSecondArray;
873    use arrow_array::UInt8Array;
874    use arrow_array::UInt16Array;
875    use arrow_array::UInt32Array;
876    use arrow_array::UInt64Array;
877    use arrow_array::builder::BinaryViewBuilder;
878    use arrow_array::builder::Decimal128Builder;
879    use arrow_array::builder::Decimal256Builder;
880    use arrow_array::builder::Int32Builder;
881    use arrow_array::builder::Int64Builder;
882    use arrow_array::builder::LargeListBuilder;
883    use arrow_array::builder::ListBuilder;
884    use arrow_array::builder::MapBuilder as ArrowMapBuilder;
885    use arrow_array::builder::StringBuilder;
886    use arrow_array::builder::StringViewBuilder;
887    use arrow_array::new_null_array;
888    use arrow_array::types::ArrowPrimitiveType;
889    use arrow_array::types::Float16Type;
890    use arrow_buffer::BooleanBuffer;
891    use arrow_buffer::Buffer as ArrowBuffer;
892    use arrow_buffer::NullBuffer;
893    use arrow_buffer::OffsetBuffer;
894    use arrow_buffer::ScalarBuffer;
895    use arrow_schema::DataType;
896    use arrow_schema::Field;
897    use arrow_schema::Fields;
898    use arrow_schema::Schema;
899    use rstest::rstest;
900    use vortex_array::IntoArray;
901    use vortex_array::VortexSessionExecute as _;
902    use vortex_array::arrays::BoolArray;
903    use vortex_array::arrays::Decimal;
904    use vortex_array::arrays::DecimalArray;
905    use vortex_array::arrays::FixedSizeList;
906    use vortex_array::arrays::FixedSizeListArray as VortexFixedSizeListArray;
907    use vortex_array::arrays::List;
908    use vortex_array::arrays::ListArray;
909    use vortex_array::arrays::ListView;
910    use vortex_array::arrays::ListViewArray;
911    use vortex_array::arrays::NullArray as VortexNullArray;
912    use vortex_array::arrays::Primitive;
913    use vortex_array::arrays::PrimitiveArray;
914    use vortex_array::arrays::Struct;
915    use vortex_array::arrays::StructArray as VortexStructArray;
916    use vortex_array::arrays::TemporalArray;
917    use vortex_array::arrays::VarBinArray;
918    use vortex_array::arrays::VarBinView;
919    use vortex_array::arrays::fixed_size_list::FixedSizeListArrayExt;
920    use vortex_array::arrays::fixed_size_list::FixedSizeListArraySlotsExt;
921    use vortex_array::arrays::list::ListArraySlotsExt;
922    use vortex_array::arrays::listview::ListViewArraySlotsExt;
923    use vortex_array::arrays::struct_::StructArrayExt;
924    use vortex_array::assert_arrays_eq;
925    use vortex_array::dtype::DType;
926    use vortex_array::dtype::DecimalDType;
927    use vortex_array::dtype::DecimalType;
928    use vortex_array::dtype::Nullability;
929    use vortex_array::dtype::PType;
930    use vortex_array::dtype::i256;
931    use vortex_array::extension::datetime::TimeUnit;
932    use vortex_array::extension::datetime::Timestamp;
933    use vortex_array::scalar::Scalar;
934    use vortex_array::validity::Validity;
935    use vortex_buffer::buffer;
936    use vortex_error::VortexResult;
937    use vortex_session::VortexSession;
938
939    use crate::IntoVortexArray as _;
940    use crate::convert::from_arrow_batch;
941    use crate::convert::from_arrow_dyn;
942    use crate::convert::from_arrow_temporal;
943
944    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
945
946    #[rstest]
947    #[case::i8(
948        Arc::new(Int8Array::from(vec![Some(1), None, Some(3), Some(4)])),
949        Arc::new(Int8Array::from(vec![1, 2, 3, 4])),
950        PType::I8,
951    )]
952    #[case::i16(
953        Arc::new(Int16Array::from(vec![Some(100), None, Some(300), Some(400)])),
954        Arc::new(Int16Array::from(vec![100, 200, 300, 400])),
955        PType::I16,
956    )]
957    #[case::i32(
958        Arc::new(Int32Array::from(vec![Some(1000), None, Some(3000), Some(4000)])),
959        Arc::new(Int32Array::from(vec![1000, 2000, 3000, 4000])),
960        PType::I32,
961    )]
962    #[case::i64(
963        Arc::new(Int64Array::from(vec![Some(10000), None, Some(30000), Some(40000)])),
964        Arc::new(Int64Array::from(vec![10000_i64, 20000, 30000, 40000])),
965        PType::I64,
966    )]
967    #[case::u8(
968        Arc::new(UInt8Array::from(vec![Some(1), None, Some(3), Some(4)])),
969        Arc::new(UInt8Array::from(vec![1_u8, 2, 3, 4])),
970        PType::U8,
971    )]
972    #[case::u16(
973        Arc::new(UInt16Array::from(vec![Some(100), None, Some(300), Some(400)])),
974        Arc::new(UInt16Array::from(vec![100_u16, 200, 300, 400])),
975        PType::U16,
976    )]
977    #[case::u32(
978        Arc::new(UInt32Array::from(vec![Some(1000), None, Some(3000), Some(4000)])),
979        Arc::new(UInt32Array::from(vec![1000_u32, 2000, 3000, 4000])),
980        PType::U32,
981    )]
982    #[case::u64(
983        Arc::new(UInt64Array::from(vec![Some(10000), None, Some(30000), Some(40000)])),
984        Arc::new(UInt64Array::from(vec![10000_u64, 20000, 30000, 40000])),
985        PType::U64,
986    )]
987    #[case::f32(
988        Arc::new(Float32Array::from(vec![Some(1.5), None, Some(3.5), Some(4.5)])),
989        Arc::new(Float32Array::from(vec![1.5_f32, 2.5, 3.5, 4.5])),
990        PType::F32,
991    )]
992    #[case::f64(
993        Arc::new(Float64Array::from(vec![Some(1.5), None, Some(3.5), Some(4.5)])),
994        Arc::new(Float64Array::from(vec![1.5_f64, 2.5, 3.5, 4.5])),
995        PType::F64,
996    )]
997    fn test_primitive_array_conversion(
998        #[case] nullable: Arc<dyn ArrowArray>,
999        #[case] non_nullable: Arc<dyn ArrowArray>,
1000        #[case] expected_ptype: PType,
1001    ) {
1002        let v_null = from_arrow_dyn(nullable.as_ref(), true).unwrap();
1003        let v_non_null = from_arrow_dyn(non_nullable.as_ref(), false).unwrap();
1004        assert_eq!(v_null.len(), 4);
1005        assert_eq!(v_non_null.len(), 4);
1006        assert_eq!(v_null.as_::<Primitive>().ptype(), expected_ptype);
1007        assert_eq!(v_non_null.as_::<Primitive>().ptype(), expected_ptype);
1008        let (expected_nullable, expected_non_nullable) = match expected_ptype {
1009            PType::I8 => (
1010                PrimitiveArray::from_option_iter([Some(1i8), None, Some(3), Some(4)]),
1011                PrimitiveArray::from_iter([1i8, 2, 3, 4]),
1012            ),
1013            PType::I16 => (
1014                PrimitiveArray::from_option_iter([Some(100i16), None, Some(300), Some(400)]),
1015                PrimitiveArray::from_iter([100i16, 200, 300, 400]),
1016            ),
1017            PType::I32 => (
1018                PrimitiveArray::from_option_iter([Some(1000i32), None, Some(3000), Some(4000)]),
1019                PrimitiveArray::from_iter([1000i32, 2000, 3000, 4000]),
1020            ),
1021            PType::I64 => (
1022                PrimitiveArray::from_option_iter([Some(10000i64), None, Some(30000), Some(40000)]),
1023                PrimitiveArray::from_iter([10000i64, 20000, 30000, 40000]),
1024            ),
1025            PType::U8 => (
1026                PrimitiveArray::from_option_iter([Some(1u8), None, Some(3), Some(4)]),
1027                PrimitiveArray::from_iter([1u8, 2, 3, 4]),
1028            ),
1029            PType::U16 => (
1030                PrimitiveArray::from_option_iter([Some(100u16), None, Some(300), Some(400)]),
1031                PrimitiveArray::from_iter([100u16, 200, 300, 400]),
1032            ),
1033            PType::U32 => (
1034                PrimitiveArray::from_option_iter([Some(1000u32), None, Some(3000), Some(4000)]),
1035                PrimitiveArray::from_iter([1000u32, 2000, 3000, 4000]),
1036            ),
1037            PType::U64 => (
1038                PrimitiveArray::from_option_iter([Some(10000u64), None, Some(30000), Some(40000)]),
1039                PrimitiveArray::from_iter([10000u64, 20000, 30000, 40000]),
1040            ),
1041            PType::F32 => (
1042                PrimitiveArray::from_option_iter([Some(1.5f32), None, Some(3.5), Some(4.5)]),
1043                PrimitiveArray::from_iter([1.5f32, 2.5, 3.5, 4.5]),
1044            ),
1045            PType::F64 => (
1046                PrimitiveArray::from_option_iter([Some(1.5f64), None, Some(3.5), Some(4.5)]),
1047                PrimitiveArray::from_iter([1.5f64, 2.5, 3.5, 4.5]),
1048            ),
1049            _ => unreachable!(),
1050        };
1051        assert_arrays_eq!(
1052            v_null,
1053            expected_nullable,
1054            &mut SESSION.create_execution_ctx()
1055        );
1056        assert_arrays_eq!(
1057            v_non_null,
1058            expected_non_nullable,
1059            &mut SESSION.create_execution_ctx()
1060        );
1061    }
1062
1063    #[test]
1064    fn test_reject_timestamp_array_invalid_timezone() {
1065        let array = TimestampSecondArray::from(vec![0]).with_timezone("Not/A/Timezone");
1066        assert!(from_arrow_temporal(&array, false).is_err());
1067    }
1068
1069    #[test]
1070    fn test_float16_array_conversion() {
1071        let values = vec![
1072            Some(<Float16Type as ArrowPrimitiveType>::Native::from_f32(1.5)),
1073            None,
1074            Some(<Float16Type as ArrowPrimitiveType>::Native::from_f32(3.5)),
1075        ];
1076        let arrow_array = arrow_array::PrimitiveArray::<Float16Type>::from(values);
1077        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1078
1079        let non_null_values = vec![
1080            <Float16Type as ArrowPrimitiveType>::Native::from_f32(1.5),
1081            <Float16Type as ArrowPrimitiveType>::Native::from_f32(2.5),
1082        ];
1083        let arrow_array_non_null =
1084            arrow_array::PrimitiveArray::<Float16Type>::from(non_null_values);
1085        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1086
1087        assert_eq!(vortex_array.len(), 3);
1088        assert_eq!(vortex_array_non_null.len(), 2);
1089
1090        // Verify metadata - should be PrimitiveArray with F16 ptype
1091        let primitive_array = vortex_array.as_::<Primitive>();
1092        assert_eq!(primitive_array.ptype(), PType::F16);
1093
1094        let primitive_array_non_null = vortex_array_non_null.as_::<Primitive>();
1095        assert_eq!(primitive_array_non_null.ptype(), PType::F16);
1096        assert_arrays_eq!(
1097            vortex_array,
1098            PrimitiveArray::from_option_iter([
1099                Some(<Float16Type as ArrowPrimitiveType>::Native::from_f32(1.5)),
1100                None,
1101                Some(<Float16Type as ArrowPrimitiveType>::Native::from_f32(3.5))
1102            ]),
1103            &mut SESSION.create_execution_ctx()
1104        );
1105        assert_arrays_eq!(
1106            vortex_array_non_null,
1107            PrimitiveArray::from_iter([
1108                <Float16Type as ArrowPrimitiveType>::Native::from_f32(1.5),
1109                <Float16Type as ArrowPrimitiveType>::Native::from_f32(2.5)
1110            ]),
1111            &mut SESSION.create_execution_ctx()
1112        );
1113    }
1114
1115    // Test decimal array conversions
1116    #[test]
1117    fn test_decimal128_array_conversion() {
1118        let mut builder = Decimal128Builder::with_capacity(4);
1119        builder.append_value(12345);
1120        builder.append_null();
1121        builder.append_value(67890);
1122        builder.append_value(11111);
1123        let decimal_array = builder.finish().with_precision_and_scale(10, 2).unwrap();
1124
1125        let vortex_array = from_arrow_dyn(&decimal_array, true).unwrap();
1126        assert_eq!(vortex_array.len(), 4);
1127
1128        let mut builder_non_null = Decimal128Builder::with_capacity(3);
1129        builder_non_null.append_value(12345);
1130        builder_non_null.append_value(67890);
1131        builder_non_null.append_value(11111);
1132        let decimal_array_non_null = builder_non_null
1133            .finish()
1134            .with_precision_and_scale(10, 2)
1135            .unwrap();
1136
1137        let vortex_array_non_null = from_arrow_dyn(&decimal_array_non_null, false).unwrap();
1138        assert_eq!(vortex_array_non_null.len(), 3);
1139
1140        // Verify metadata: a DecimalArray with the precision, scale and canonical width
1141        let decimal_vortex_array = vortex_array.as_::<Decimal>();
1142        assert_eq!(decimal_vortex_array.decimal_dtype().precision(), 10);
1143        assert_eq!(decimal_vortex_array.decimal_dtype().scale(), 2);
1144        assert_eq!(decimal_vortex_array.values_type(), DecimalType::I64);
1145
1146        let decimal_vortex_array_non_null = vortex_array_non_null.as_::<Decimal>();
1147        assert_eq!(
1148            decimal_vortex_array_non_null.decimal_dtype().precision(),
1149            10
1150        );
1151        assert_eq!(decimal_vortex_array_non_null.decimal_dtype().scale(), 2);
1152        assert_eq!(
1153            decimal_vortex_array_non_null.values_type(),
1154            DecimalType::I64
1155        );
1156        assert_arrays_eq!(
1157            vortex_array,
1158            DecimalArray::from_option_iter(
1159                [Some(12345i64), None, Some(67890i64), Some(11111i64)],
1160                DecimalDType::new(10, 2)
1161            ),
1162            &mut SESSION.create_execution_ctx()
1163        );
1164        assert_arrays_eq!(
1165            vortex_array_non_null,
1166            DecimalArray::from_iter([12345i64, 67890i64, 11111i64], DecimalDType::new(10, 2)),
1167            &mut SESSION.create_execution_ctx()
1168        );
1169    }
1170
1171    #[test]
1172    fn test_decimal256_array_conversion() {
1173        let mut builder = Decimal256Builder::with_capacity(4);
1174        builder.append_value(arrow_buffer::i256::from_i128(12345));
1175        builder.append_null();
1176        builder.append_value(arrow_buffer::i256::from_i128(67890));
1177        builder.append_value(arrow_buffer::i256::from_i128(11111));
1178        let decimal_array = builder.finish().with_precision_and_scale(38, 10).unwrap();
1179
1180        let vortex_array = from_arrow_dyn(&decimal_array, true).unwrap();
1181        assert_eq!(vortex_array.len(), 4);
1182
1183        let mut builder_non_null = Decimal256Builder::with_capacity(3);
1184        builder_non_null.append_value(arrow_buffer::i256::from_i128(12345));
1185        builder_non_null.append_value(arrow_buffer::i256::from_i128(67890));
1186        builder_non_null.append_value(arrow_buffer::i256::from_i128(11111));
1187        let decimal_array_non_null = builder_non_null
1188            .finish()
1189            .with_precision_and_scale(38, 10)
1190            .unwrap();
1191
1192        let vortex_array_non_null = from_arrow_dyn(&decimal_array_non_null, false).unwrap();
1193        assert_eq!(vortex_array_non_null.len(), 3);
1194
1195        // Verify metadata: a DecimalArray with the precision, scale and canonical width
1196        let decimal_vortex_array = vortex_array.as_::<Decimal>();
1197        assert_eq!(decimal_vortex_array.decimal_dtype().precision(), 38);
1198        assert_eq!(decimal_vortex_array.decimal_dtype().scale(), 10);
1199        assert_eq!(decimal_vortex_array.values_type(), DecimalType::I128);
1200
1201        let decimal_vortex_array_non_null = vortex_array_non_null.as_::<Decimal>();
1202        assert_eq!(
1203            decimal_vortex_array_non_null.decimal_dtype().precision(),
1204            38
1205        );
1206        assert_eq!(decimal_vortex_array_non_null.decimal_dtype().scale(), 10);
1207        assert_eq!(
1208            decimal_vortex_array_non_null.values_type(),
1209            DecimalType::I128
1210        );
1211        assert_arrays_eq!(
1212            vortex_array,
1213            DecimalArray::from_option_iter(
1214                [Some(12345i128), None, Some(67890i128), Some(11111i128)],
1215                DecimalDType::new(38, 10)
1216            ),
1217            &mut SESSION.create_execution_ctx()
1218        );
1219        assert_arrays_eq!(
1220            vortex_array_non_null,
1221            DecimalArray::from_iter([12345i128, 67890i128, 11111i128], DecimalDType::new(38, 10)),
1222            &mut SESSION.create_execution_ctx()
1223        );
1224    }
1225
1226    #[rstest]
1227    #[case::decimal32_p4(DataType::Decimal32(4, 2), DecimalType::I16, false)]
1228    #[case::decimal64_p9(DataType::Decimal64(9, 2), DecimalType::I32, false)]
1229    #[case::decimal128_p5(DataType::Decimal128(5, 2), DecimalType::I32, false)]
1230    #[case::decimal128_p18(DataType::Decimal128(18, 2), DecimalType::I64, false)]
1231    #[case::decimal128_p38(DataType::Decimal128(38, 2), DecimalType::I128, true)]
1232    #[case::decimal256_p38(DataType::Decimal256(38, 2), DecimalType::I128, false)]
1233    #[case::decimal256_p40(DataType::Decimal256(40, 2), DecimalType::I256, true)]
1234    fn test_decimal_import_canonical_width(
1235        #[case] data_type: DataType,
1236        #[case] values_type: DecimalType,
1237        #[case] zero_copy: bool,
1238    ) -> VortexResult<()> {
1239        let (precision, scale) = match data_type {
1240            DataType::Decimal32(precision, scale)
1241            | DataType::Decimal64(precision, scale)
1242            | DataType::Decimal128(precision, scale)
1243            | DataType::Decimal256(precision, scale) => (precision, scale),
1244            _ => unreachable!("every case is an Arrow decimal type, got {data_type}"),
1245        };
1246
1247        // The largest and smallest values of the precision, around a null and a zero.
1248        let max = i256::from_i128(10).wrapping_pow(u32::from(precision)) - i256::ONE;
1249        let values = [Some(-max), None, Some(i256::ZERO), Some(max)];
1250        let arrow_values = values.map(|value| value.map(arrow_buffer::i256::from));
1251        let bounds =
1252            Decimal256Array::from_iter(arrow_values).with_precision_and_scale(precision, scale)?;
1253        let arrow = arrow_cast::cast(&bounds, &data_type)?;
1254
1255        let imported = from_arrow_dyn(arrow.as_ref(), true)?;
1256        let decimal = imported.as_::<Decimal>();
1257        assert_eq!(decimal.values_type(), values_type);
1258        if zero_copy {
1259            assert_eq!(
1260                decimal.buffer_handle().as_host().as_ptr(),
1261                arrow.to_data().buffers()[0].as_ptr()
1262            );
1263        }
1264
1265        assert_arrays_eq!(
1266            imported,
1267            DecimalArray::from_option_iter(values, DecimalDType::new(precision, scale)),
1268            &mut SESSION.create_execution_ctx()
1269        );
1270        Ok(())
1271    }
1272
1273    /// The null slot holds 10^30, which is outside both precisions and does not fit `i32`.
1274    #[rstest]
1275    #[case::narrowing(5, false)]
1276    #[case::equal_width(20, true)]
1277    fn test_decimal_import_ignores_null_slots(
1278        #[case] precision: u8,
1279        #[case] zero_copy: bool,
1280    ) -> VortexResult<()> {
1281        let arrow = Decimal128Array::new(
1282            ScalarBuffer::from(vec![12_345, 10i128.pow(30), -12_345]),
1283            Some(NullBuffer::from(vec![true, false, true])),
1284        )
1285        .with_precision_and_scale(precision, 2)?;
1286
1287        let imported = from_arrow_dyn(&arrow, true)?;
1288        let decimal = imported.as_::<Decimal>();
1289        if zero_copy {
1290            assert_eq!(
1291                decimal.buffer_handle().as_host().as_ptr(),
1292                arrow.to_data().buffers()[0].as_ptr()
1293            );
1294        } else {
1295            // A narrowing copy writes zeros into the null slots.
1296            assert_eq!(decimal.values_type(), DecimalType::I32);
1297            assert_eq!(decimal.buffer::<i32>().as_slice(), &[12_345, 0, -12_345]);
1298        }
1299
1300        assert_arrays_eq!(
1301            imported,
1302            DecimalArray::from_option_iter(
1303                [Some(12_345i128), None, Some(-12_345)],
1304                DecimalDType::new(precision, 2)
1305            ),
1306            &mut SESSION.create_execution_ctx()
1307        );
1308        Ok(())
1309    }
1310
1311    #[test]
1312    fn test_decimal_import_rejects_value_outside_precision() -> VortexResult<()> {
1313        let arrow =
1314            Decimal128Array::from(vec![12_345, 1_000_000]).with_precision_and_scale(5, 2)?;
1315
1316        let err = from_arrow_dyn(&arrow, true)
1317            .expect_err("a valid value outside the precision must fail the import");
1318        let message = err.to_string();
1319        assert!(message.contains("row 1"), "{message}");
1320        assert!(message.contains("null_if_overflow_precision"), "{message}");
1321        Ok(())
1322    }
1323
1324    #[test]
1325    fn test_decimal_import_zero_copy_rejects_value_outside_precision() -> VortexResult<()> {
1326        let arrow =
1327            Decimal128Array::from(vec![12_345, 10i128.pow(20)]).with_precision_and_scale(20, 2)?;
1328
1329        let err = from_arrow_dyn(&arrow, true)
1330            .expect_err("a valid value outside the precision must fail the import");
1331        let message = err.to_string();
1332        assert!(message.contains("row 1"), "{message}");
1333        assert!(message.contains("null_if_overflow_precision"), "{message}");
1334        Ok(())
1335    }
1336
1337    #[rstest]
1338    #[case::precision_zero(DataType::Decimal128(0, 0))]
1339    #[case::precision_above_max(DataType::Decimal128(77, 0))]
1340    #[case::scale_above_precision(DataType::Decimal128(5, 6))]
1341    fn test_decimal_import_rejects_invalid_precision(#[case] data_type: DataType) {
1342        // `with_data_type` does not validate the precision or scale, as an FFI import would not.
1343        let arrow = Decimal128Array::from(vec![1]).with_data_type(data_type);
1344
1345        assert!(from_arrow_dyn(&arrow, true).is_err());
1346    }
1347
1348    // Test temporal array conversions
1349    #[rstest]
1350    #[case::timestamp_second(
1351        Arc::new(TimestampSecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1352        Arc::new(TimestampSecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1353    )]
1354    #[case::timestamp_millisecond(
1355        Arc::new(TimestampMillisecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1356        Arc::new(TimestampMillisecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1357    )]
1358    #[case::timestamp_microsecond(
1359        Arc::new(TimestampMicrosecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1360        Arc::new(TimestampMicrosecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1361    )]
1362    #[case::timestamp_nanosecond(
1363        Arc::new(TimestampNanosecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1364        Arc::new(TimestampNanosecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1365    )]
1366    #[case::time32_second(
1367        Arc::new(Time32SecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1368        Arc::new(Time32SecondArray::from(vec![1000_i32, 2000, 3000, 4000])),
1369    )]
1370    #[case::time32_millisecond(
1371        Arc::new(Time32MillisecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1372        Arc::new(Time32MillisecondArray::from(vec![1000_i32, 2000, 3000, 4000])),
1373    )]
1374    #[case::time64_microsecond(
1375        Arc::new(Time64MicrosecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1376        Arc::new(Time64MicrosecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1377    )]
1378    #[case::time64_nanosecond(
1379        Arc::new(Time64NanosecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1380        Arc::new(Time64NanosecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1381    )]
1382    #[case::date32(
1383        Arc::new(Date32Array::from(vec![Some(18000), None, Some(18002), Some(18003)])),
1384        Arc::new(Date32Array::from(vec![18000_i32, 18001, 18002, 18003])),
1385    )]
1386    #[case::date64(
1387        Arc::new(Date64Array::from(vec![Some(1555200000000), None, Some(1555286400000), Some(1555372800000)]
1388        )),
1389        Arc::new(Date64Array::from(vec![1555200000000_i64, 1555213600000, 1555286400000, 1555372800000]
1390        )),
1391    )]
1392    fn test_temporal_array_conversion(
1393        #[case] nullable: Arc<dyn ArrowArray>,
1394        #[case] non_nullable: Arc<dyn ArrowArray>,
1395    ) {
1396        let v_null = from_arrow_dyn(nullable.as_ref(), true).unwrap();
1397        let v_non_null = from_arrow_dyn(non_nullable.as_ref(), false).unwrap();
1398        assert_eq!(v_null.len(), 4);
1399        assert_eq!(v_non_null.len(), 4);
1400        let expected = |nullable: bool| {
1401            let i32_values = if nullable {
1402                PrimitiveArray::from_option_iter([Some(1000i32), None, Some(3000), Some(4000)])
1403            } else {
1404                PrimitiveArray::from_iter([1000i32, 2000, 3000, 4000])
1405            }
1406            .into_array();
1407            let i64_values = if nullable {
1408                PrimitiveArray::from_option_iter([Some(1000i64), None, Some(3000), Some(4000)])
1409            } else {
1410                PrimitiveArray::from_iter([1000i64, 2000, 3000, 4000])
1411            }
1412            .into_array();
1413            match non_nullable.data_type() {
1414                DataType::Timestamp(unit, _) => {
1415                    let unit = match unit {
1416                        arrow_schema::TimeUnit::Second => TimeUnit::Seconds,
1417                        arrow_schema::TimeUnit::Millisecond => TimeUnit::Milliseconds,
1418                        arrow_schema::TimeUnit::Microsecond => TimeUnit::Microseconds,
1419                        arrow_schema::TimeUnit::Nanosecond => TimeUnit::Nanoseconds,
1420                    };
1421                    TemporalArray::new_timestamp(i64_values, unit, None).into_array()
1422                }
1423                DataType::Time32(arrow_schema::TimeUnit::Second) => {
1424                    TemporalArray::new_time(i32_values, TimeUnit::Seconds).into_array()
1425                }
1426                DataType::Time32(arrow_schema::TimeUnit::Millisecond) => {
1427                    TemporalArray::new_time(i32_values, TimeUnit::Milliseconds).into_array()
1428                }
1429                DataType::Time64(arrow_schema::TimeUnit::Microsecond) => {
1430                    TemporalArray::new_time(i64_values, TimeUnit::Microseconds).into_array()
1431                }
1432                DataType::Time64(arrow_schema::TimeUnit::Nanosecond) => {
1433                    TemporalArray::new_time(i64_values, TimeUnit::Nanoseconds).into_array()
1434                }
1435                DataType::Date32 => TemporalArray::new_date(
1436                    if nullable {
1437                        PrimitiveArray::from_option_iter([
1438                            Some(18000i32),
1439                            None,
1440                            Some(18002),
1441                            Some(18003),
1442                        ])
1443                    } else {
1444                        PrimitiveArray::from_iter([18000i32, 18001, 18002, 18003])
1445                    }
1446                    .into_array(),
1447                    TimeUnit::Days,
1448                )
1449                .into_array(),
1450                DataType::Date64 => TemporalArray::new_date(
1451                    if nullable {
1452                        PrimitiveArray::from_option_iter([
1453                            Some(1555200000000i64),
1454                            None,
1455                            Some(1555286400000),
1456                            Some(1555372800000),
1457                        ])
1458                    } else {
1459                        PrimitiveArray::from_iter([
1460                            1555200000000i64,
1461                            1555213600000,
1462                            1555286400000,
1463                            1555372800000,
1464                        ])
1465                    }
1466                    .into_array(),
1467                    TimeUnit::Milliseconds,
1468                )
1469                .into_array(),
1470                _ => unreachable!(),
1471            }
1472        };
1473        assert_arrays_eq!(v_null, expected(true), &mut SESSION.create_execution_ctx());
1474        assert_arrays_eq!(
1475            v_non_null,
1476            expected(false),
1477            &mut SESSION.create_execution_ctx()
1478        );
1479    }
1480
1481    #[test]
1482    fn test_timestamp_timezone_microsecond_array_conversion() {
1483        let arrow_array =
1484            TimestampMicrosecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])
1485                .with_timezone("UTC");
1486        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1487
1488        let arrow_array_non_null =
1489            TimestampMicrosecondArray::from(vec![1000_i64, 2000, 3000, 4000]).with_timezone("UTC");
1490        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1491
1492        assert_eq!(vortex_array.len(), 4);
1493        assert_eq!(
1494            vortex_array.dtype(),
1495            &DType::Extension(
1496                Timestamp::new_with_tz(
1497                    TimeUnit::Microseconds,
1498                    Some("UTC".into()),
1499                    Nullability::Nullable
1500                )
1501                .erased()
1502            ),
1503        );
1504        assert_eq!(vortex_array_non_null.len(), 4);
1505        assert_eq!(
1506            vortex_array_non_null.dtype(),
1507            &DType::Extension(
1508                Timestamp::new_with_tz(
1509                    TimeUnit::Microseconds,
1510                    Some("UTC".into()),
1511                    Nullability::NonNullable
1512                )
1513                .erased()
1514            )
1515        );
1516        assert_arrays_eq!(
1517            vortex_array,
1518            TemporalArray::new_timestamp(
1519                PrimitiveArray::from_option_iter([Some(1000i64), None, Some(3000), Some(4000)])
1520                    .into_array(),
1521                TimeUnit::Microseconds,
1522                Some("UTC".into())
1523            ),
1524            &mut SESSION.create_execution_ctx()
1525        );
1526        assert_arrays_eq!(
1527            vortex_array_non_null,
1528            TemporalArray::new_timestamp(
1529                buffer![1000i64, 2000, 3000, 4000].into_array(),
1530                TimeUnit::Microseconds,
1531                Some("UTC".into())
1532            ),
1533            &mut SESSION.create_execution_ctx()
1534        );
1535    }
1536
1537    // Test string/binary array conversions
1538    #[rstest]
1539    #[case::utf8(
1540        Arc::new(StringArray::from(vec![Some("hello"), None, Some("world"), Some("test")])),
1541        Arc::new(StringArray::from(vec!["hello", "world", "test", "vortex"])),
1542        DType::Utf8(Nullability::NonNullable),
1543    )]
1544    #[case::large_utf8(
1545        Arc::new(LargeStringArray::from(vec![Some("hello"), None, Some("world"), Some("test")])),
1546        Arc::new(LargeStringArray::from(vec!["hello", "world", "test", "vortex"])),
1547        DType::Utf8(Nullability::NonNullable),
1548    )]
1549    #[case::binary(
1550        Arc::new(BinaryArray::from(vec![
1551            Some("hello".as_bytes()), None, Some("world".as_bytes()), Some("test".as_bytes()),
1552        ])),
1553        Arc::new(BinaryArray::from(vec![
1554            "hello".as_bytes(), "world".as_bytes(), "test".as_bytes(), "vortex".as_bytes(),
1555        ])),
1556        DType::Binary(Nullability::NonNullable),
1557    )]
1558    #[case::large_binary(
1559        Arc::new(LargeBinaryArray::from(vec![
1560            Some("hello".as_bytes()), None, Some("world".as_bytes()), Some("test".as_bytes()),
1561        ])),
1562        Arc::new(LargeBinaryArray::from(vec![
1563            "hello".as_bytes(), "world".as_bytes(), "test".as_bytes(), "vortex".as_bytes(),
1564        ])),
1565        DType::Binary(Nullability::NonNullable),
1566    )]
1567    fn test_string_binary_array_conversion(
1568        #[case] nullable: Arc<dyn ArrowArray>,
1569        #[case] non_nullable: Arc<dyn ArrowArray>,
1570        #[case] expected_non_nullable_dtype: DType,
1571    ) {
1572        let v_null = from_arrow_dyn(nullable.as_ref(), true).unwrap();
1573        let v_non_null = from_arrow_dyn(non_nullable.as_ref(), false).unwrap();
1574        assert_eq!(v_null.len(), 4);
1575        assert_eq!(v_non_null.len(), 4);
1576        assert_eq!(v_null.dtype(), &expected_non_nullable_dtype.as_nullable());
1577        assert_eq!(v_non_null.dtype(), &expected_non_nullable_dtype);
1578        assert_arrays_eq!(
1579            v_null,
1580            VarBinArray::from_iter(
1581                [Some("hello"), None, Some("world"), Some("test")],
1582                expected_non_nullable_dtype.as_nullable()
1583            ),
1584            &mut SESSION.create_execution_ctx()
1585        );
1586        assert_arrays_eq!(
1587            v_non_null,
1588            VarBinArray::from_iter_nonnull(
1589                ["hello", "world", "test", "vortex"],
1590                expected_non_nullable_dtype
1591            ),
1592            &mut SESSION.create_execution_ctx()
1593        );
1594    }
1595
1596    #[test]
1597    fn test_utf8_view_array_conversion() {
1598        let mut builder = StringViewBuilder::new();
1599        builder.append_value("hello");
1600        builder.append_null();
1601        builder.append_value("world");
1602        builder.append_value("test");
1603        let arrow_array = builder.finish();
1604        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1605
1606        let mut builder_non_null = StringViewBuilder::new();
1607        builder_non_null.append_value("hello");
1608        builder_non_null.append_value("world");
1609        builder_non_null.append_value("test");
1610        builder_non_null.append_value("vortex");
1611        let arrow_array_non_null = builder_non_null.finish();
1612        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1613
1614        assert_eq!(vortex_array.len(), 4);
1615        assert_eq!(vortex_array_non_null.len(), 4);
1616
1617        // Verify metadata - should be VarBinViewArray with correct buffer count and dtype
1618        let varbin_view_array = vortex_array.as_::<VarBinView>();
1619        assert_eq!(
1620            varbin_view_array.data_buffers().len(),
1621            arrow_array.data_buffers().len()
1622        );
1623        assert_eq!(varbin_view_array.dtype(), &DType::Utf8(true.into()));
1624
1625        let varbin_view_array_non_null = vortex_array_non_null.as_::<VarBinView>();
1626        assert_eq!(
1627            varbin_view_array_non_null.data_buffers().len(),
1628            arrow_array_non_null.data_buffers().len()
1629        );
1630        assert_eq!(
1631            varbin_view_array_non_null.dtype(),
1632            &DType::Utf8(false.into())
1633        );
1634        assert_arrays_eq!(
1635            vortex_array,
1636            VarBinArray::from_iter(
1637                [Some("hello"), None, Some("world"), Some("test")],
1638                DType::Utf8(Nullability::NonNullable).as_nullable()
1639            ),
1640            &mut SESSION.create_execution_ctx()
1641        );
1642        assert_arrays_eq!(
1643            vortex_array_non_null,
1644            VarBinArray::from_iter_nonnull(
1645                ["hello", "world", "test", "vortex"],
1646                DType::Utf8(Nullability::NonNullable)
1647            ),
1648            &mut SESSION.create_execution_ctx()
1649        );
1650    }
1651
1652    #[test]
1653    fn test_binary_view_array_conversion() {
1654        let mut builder = BinaryViewBuilder::new();
1655        builder.append_value(b"hello");
1656        builder.append_null();
1657        builder.append_value(b"world");
1658        builder.append_value(b"test");
1659        let arrow_array = builder.finish();
1660        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1661
1662        let mut builder_non_null = BinaryViewBuilder::new();
1663        builder_non_null.append_value(b"hello");
1664        builder_non_null.append_value(b"world");
1665        builder_non_null.append_value(b"test");
1666        builder_non_null.append_value(b"vortex");
1667        let arrow_array_non_null = builder_non_null.finish();
1668        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1669
1670        assert_eq!(vortex_array.len(), 4);
1671        assert_eq!(vortex_array_non_null.len(), 4);
1672
1673        // Verify metadata - should be VarBinViewArray with correct buffer count and dtype
1674        let varbin_view_array = vortex_array.as_::<VarBinView>();
1675        assert_eq!(
1676            varbin_view_array.data_buffers().len(),
1677            arrow_array.data_buffers().len()
1678        );
1679        assert_eq!(varbin_view_array.dtype(), &DType::Binary(true.into()));
1680
1681        let varbin_view_array_non_null = vortex_array_non_null.as_::<VarBinView>();
1682        assert_eq!(
1683            varbin_view_array_non_null.data_buffers().len(),
1684            arrow_array_non_null.data_buffers().len()
1685        );
1686        assert_eq!(
1687            varbin_view_array_non_null.dtype(),
1688            &DType::Binary(false.into())
1689        );
1690        assert_arrays_eq!(
1691            vortex_array,
1692            VarBinArray::from_iter(
1693                [Some("hello"), None, Some("world"), Some("test")],
1694                DType::Binary(Nullability::NonNullable).as_nullable()
1695            ),
1696            &mut SESSION.create_execution_ctx()
1697        );
1698        assert_arrays_eq!(
1699            vortex_array_non_null,
1700            VarBinArray::from_iter_nonnull(
1701                ["hello", "world", "test", "vortex"],
1702                DType::Binary(Nullability::NonNullable)
1703            ),
1704            &mut SESSION.create_execution_ctx()
1705        );
1706    }
1707
1708    // Test boolean array conversions
1709    #[test]
1710    fn test_boolean_array_conversion() {
1711        let arrow_array = BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]);
1712        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1713
1714        let arrow_array_non_null = BooleanArray::from(vec![true, false, true, false]);
1715        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1716
1717        assert_eq!(vortex_array.len(), 4);
1718        assert_eq!(vortex_array_non_null.len(), 4);
1719        assert_arrays_eq!(
1720            vortex_array,
1721            BoolArray::from_iter([Some(true), None, Some(false), Some(true)]),
1722            &mut SESSION.create_execution_ctx()
1723        );
1724        assert_arrays_eq!(
1725            vortex_array_non_null,
1726            BoolArray::from_iter([true, false, true, false]),
1727            &mut SESSION.create_execution_ctx()
1728        );
1729    }
1730
1731    // Test struct array conversions
1732    #[test]
1733    fn test_struct_array_conversion() {
1734        let fields = vec![
1735            Field::new("field1", DataType::Int32, true),
1736            Field::new("field2", DataType::Utf8, false),
1737        ];
1738        let schema = Fields::from(fields);
1739
1740        let field1_data = Int32Array::from(vec![Some(1), None, Some(3)]);
1741        let field2_data = StringArray::from(vec!["a", "b", "c"]);
1742
1743        let arrow_array = StructArray::new(
1744            schema.clone(),
1745            vec![Arc::new(field1_data), Arc::new(field2_data)],
1746            None,
1747        );
1748
1749        let vortex_array = from_arrow_dyn(&arrow_array, false).unwrap();
1750        assert_eq!(vortex_array.len(), 3);
1751
1752        // Verify metadata - should be StructArray with correct field names
1753        let struct_vortex_array = vortex_array.as_::<Struct>();
1754        assert_eq!(struct_vortex_array.names().len(), 2);
1755        assert_eq!(struct_vortex_array.names()[0], "field1");
1756        assert_eq!(struct_vortex_array.names()[1], "field2");
1757
1758        // Test nullable struct
1759        let nullable_array = StructArray::new(
1760            schema,
1761            vec![
1762                Arc::new(Int32Array::from(vec![Some(1), None, Some(3)])),
1763                Arc::new(StringArray::from(vec!["a", "b", "c"])),
1764            ],
1765            Some(NullBuffer::new(BooleanBuffer::from(vec![
1766                true, false, true,
1767            ]))),
1768        );
1769
1770        let vortex_nullable_array = from_arrow_dyn(&nullable_array, true).unwrap();
1771        assert_eq!(vortex_nullable_array.len(), 3);
1772
1773        // Verify metadata for nullable struct
1774        let struct_vortex_nullable_array = vortex_nullable_array.as_::<Struct>();
1775        assert_eq!(struct_vortex_nullable_array.names().len(), 2);
1776        assert_eq!(struct_vortex_nullable_array.names()[0], "field1");
1777        assert_eq!(struct_vortex_nullable_array.names()[1], "field2");
1778        let expected = |validity| {
1779            VortexStructArray::new(
1780                ["field1", "field2"].into(),
1781                vec![
1782                    PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array(),
1783                    VarBinArray::from_iter_nonnull(
1784                        ["a", "b", "c"],
1785                        DType::Utf8(Nullability::NonNullable),
1786                    )
1787                    .into_array(),
1788                ],
1789                3,
1790                validity,
1791            )
1792        };
1793        assert_arrays_eq!(
1794            vortex_array,
1795            expected(Validity::NonNullable),
1796            &mut SESSION.create_execution_ctx()
1797        );
1798        assert_arrays_eq!(
1799            vortex_nullable_array,
1800            expected(Validity::from_iter([true, false, true])),
1801            &mut SESSION.create_execution_ctx()
1802        );
1803    }
1804
1805    // Test list array conversions
1806    #[test]
1807    fn test_list_array_conversion() {
1808        let mut ctx = SESSION.create_execution_ctx();
1809        let mut builder = ListBuilder::new(Int32Builder::new());
1810        builder.append_value([Some(1), None, Some(3)]);
1811        builder.append_null();
1812        builder.append_value([Some(4), Some(5)]);
1813        let arrow_array = builder.finish();
1814
1815        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1816        assert_eq!(vortex_array.len(), 3);
1817
1818        // Verify metadata - should be ListArray with correct offsets
1819        let list_vortex_array = vortex_array.as_::<List>();
1820        let offsets_array = list_vortex_array.offsets().as_::<Primitive>();
1821        assert_eq!(offsets_array.len(), 4); // n+1 offsets for n lists
1822        assert_eq!(offsets_array.ptype(), PType::I32);
1823
1824        // Test non-nullable list
1825        let mut builder_non_null = ListBuilder::new(Int32Builder::new());
1826        builder_non_null.append_value([Some(1), None, Some(3)]);
1827        builder_non_null.append_value([Some(4), Some(5)]);
1828        let arrow_array_non_null = builder_non_null.finish();
1829
1830        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1831        assert_eq!(vortex_array_non_null.len(), 2);
1832
1833        // Verify metadata for non-nullable list
1834        let list_vortex_array_non_null = vortex_array_non_null.as_::<List>();
1835        let offsets_array_non_null = list_vortex_array_non_null.offsets().as_::<Primitive>();
1836        assert_eq!(offsets_array_non_null.len(), 3); // n+1 offsets for n lists
1837        assert_eq!(offsets_array_non_null.ptype(), PType::I32);
1838
1839        let expected_elements =
1840            PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), Some(4), Some(5)])
1841                .into_array();
1842        let expected = ListArray::new(
1843            expected_elements.clone(),
1844            buffer![0u32, 3, 3, 5].into_array(),
1845            Validity::from_iter([true, false, true]),
1846            &mut ctx,
1847        );
1848        assert_arrays_eq!(vortex_array, expected, &mut SESSION.create_execution_ctx());
1849        let expected = ListArray::new(
1850            expected_elements,
1851            buffer![0u32, 3, 5].into_array(),
1852            Validity::NonNullable,
1853            &mut ctx,
1854        );
1855        assert_arrays_eq!(
1856            vortex_array_non_null,
1857            expected,
1858            &mut SESSION.create_execution_ctx()
1859        );
1860    }
1861
1862    #[test]
1863    fn test_sliced_offset_arrays_import_only_their_rows() -> VortexResult<()> {
1864        let strings = |rows: Range<i64>| {
1865            StringArray::from_iter_values(rows.map(|row| format!("value-{row}")))
1866        };
1867        let lists = |rows: Range<i64>| {
1868            let mut builder = ListBuilder::new(Int64Builder::new());
1869            for row in rows {
1870                builder.append_value([Some(row), Some(row + 1)]);
1871            }
1872            builder.finish()
1873        };
1874        let mut ctx = SESSION.create_execution_ctx();
1875
1876        // A slice keeps its parent's whole child; the import must not.
1877        let sliced = from_arrow_dyn(&strings(0..1000).slice(500, 2), false)?;
1878        let fresh = from_arrow_dyn(&strings(500..502), false)?;
1879        assert_eq!(sliced.nbytes(), fresh.nbytes());
1880        let expected = VarBinArray::from_iter_nonnull(
1881            ["value-500", "value-501"],
1882            DType::Utf8(Nullability::NonNullable),
1883        );
1884        assert_arrays_eq!(sliced, expected, &mut ctx);
1885        assert_arrays_eq!(fresh, expected, &mut ctx);
1886
1887        let sliced = from_arrow_dyn(&lists(0..1000).slice(500, 2), false)?;
1888        let fresh = from_arrow_dyn(&lists(500..502), false)?;
1889        assert_eq!(sliced.nbytes(), fresh.nbytes());
1890        let expected = ListArray::new(
1891            PrimitiveArray::from_option_iter([Some(500i64), Some(501), Some(501), Some(502)])
1892                .into_array(),
1893            buffer![0u32, 2, 4].into_array(),
1894            Validity::NonNullable,
1895            &mut ctx,
1896        );
1897        assert_arrays_eq!(sliced, expected, &mut ctx);
1898        assert_arrays_eq!(fresh, expected, &mut ctx);
1899        Ok(())
1900    }
1901
1902    #[test]
1903    fn test_large_list_array_conversion() {
1904        let mut ctx = SESSION.create_execution_ctx();
1905        let mut builder = LargeListBuilder::new(Int32Builder::new());
1906        builder.append_value([Some(1), None, Some(3)]);
1907        builder.append_null();
1908        builder.append_value([Some(4), Some(5)]);
1909        let arrow_array = builder.finish();
1910
1911        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1912        assert_eq!(vortex_array.len(), 3);
1913
1914        // Verify metadata - should be ListArray with correct offsets (I64 for large lists)
1915        let list_vortex_array = vortex_array.as_::<List>();
1916        let offsets_array = list_vortex_array.offsets().as_::<Primitive>();
1917        assert_eq!(offsets_array.len(), 4); // n+1 offsets for n lists
1918        assert_eq!(offsets_array.ptype(), PType::I64); // Large lists use I64 offsets
1919
1920        // Test non-nullable large list
1921        let mut builder_non_null = LargeListBuilder::new(Int32Builder::new());
1922        builder_non_null.append_value([Some(1), None, Some(3)]);
1923        builder_non_null.append_value([Some(4), Some(5)]);
1924        let arrow_array_non_null = builder_non_null.finish();
1925
1926        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1927        assert_eq!(vortex_array_non_null.len(), 2);
1928
1929        // Verify metadata for non-nullable large list
1930        let list_vortex_array_non_null = vortex_array_non_null.as_::<List>();
1931        let offsets_array_non_null = list_vortex_array_non_null.offsets().as_::<Primitive>();
1932        assert_eq!(offsets_array_non_null.len(), 3); // n+1 offsets for n lists
1933        assert_eq!(offsets_array_non_null.ptype(), PType::I64); // Large lists use I64 offsets
1934
1935        let expected_elements =
1936            PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), Some(4), Some(5)])
1937                .into_array();
1938        let expected = ListArray::new(
1939            expected_elements.clone(),
1940            buffer![0u32, 3, 3, 5].into_array(),
1941            Validity::from_iter([true, false, true]),
1942            &mut ctx,
1943        );
1944        assert_arrays_eq!(vortex_array, expected, &mut SESSION.create_execution_ctx());
1945        let expected = ListArray::new(
1946            expected_elements,
1947            buffer![0u32, 3, 5].into_array(),
1948            Validity::NonNullable,
1949            &mut ctx,
1950        );
1951        assert_arrays_eq!(
1952            vortex_array_non_null,
1953            expected,
1954            &mut SESSION.create_execution_ctx()
1955        );
1956    }
1957
1958    #[test]
1959    fn test_fixed_size_list_array_conversion() {
1960        // Create elements for the fixed-size lists
1961        let values = Int32Array::from(vec![
1962            Some(1),
1963            Some(2),
1964            Some(3), // First list
1965            Some(4),
1966            None,
1967            Some(6), // Second list (with null element)
1968            Some(7),
1969            Some(8),
1970            Some(9), // Third list
1971            Some(10),
1972            Some(11),
1973            Some(12), // Fourth list
1974        ]);
1975
1976        // Create a FixedSizeListArray with list_size=3
1977        let field = Arc::new(Field::new("item", DataType::Int32, true));
1978        let arrow_array =
1979            ArrowFixedSizeListArray::try_new(Arc::clone(&field), 3, Arc::new(values), None)
1980                .unwrap();
1981        let vortex_array = from_arrow_dyn(&arrow_array, false).unwrap();
1982
1983        assert_eq!(vortex_array.len(), 4);
1984
1985        // Verify metadata - should be FixedSizeListArray with correct list size
1986        let fsl_vortex_array = vortex_array.as_::<FixedSizeList>();
1987        assert_eq!(fsl_vortex_array.list_size(), 3);
1988        assert_eq!(fsl_vortex_array.elements().len(), 12); // 4 lists * 3 elements
1989
1990        // Test nullable fixed-size list
1991        let values_nullable = Int32Array::from(vec![
1992            Some(1),
1993            Some(2),
1994            Some(3), // First list
1995            Some(4),
1996            None,
1997            Some(6), // Second list (will be null)
1998            Some(7),
1999            Some(8),
2000            Some(9), // Third list
2001        ]);
2002
2003        // Create nulls buffer - second list is null
2004        let null_buffer = NullBuffer::new(BooleanBuffer::from(vec![true, false, true]));
2005
2006        let arrow_array_nullable = ArrowFixedSizeListArray::try_new(
2007            field,
2008            3,
2009            Arc::new(values_nullable),
2010            Some(null_buffer),
2011        )
2012        .unwrap();
2013        let vortex_array_nullable = from_arrow_dyn(&arrow_array_nullable, true).unwrap();
2014
2015        assert_eq!(vortex_array_nullable.len(), 3);
2016
2017        // Verify metadata for nullable array
2018        let fsl_vortex_array_nullable = vortex_array_nullable.as_::<FixedSizeList>();
2019        assert_eq!(fsl_vortex_array_nullable.list_size(), 3);
2020        assert_eq!(fsl_vortex_array_nullable.elements().len(), 9); // 3 lists * 3 elements
2021        assert_arrays_eq!(
2022            vortex_array,
2023            VortexFixedSizeListArray::new(
2024                PrimitiveArray::from_option_iter([
2025                    Some(1i32),
2026                    Some(2),
2027                    Some(3),
2028                    Some(4),
2029                    None,
2030                    Some(6),
2031                    Some(7),
2032                    Some(8),
2033                    Some(9),
2034                    Some(10),
2035                    Some(11),
2036                    Some(12)
2037                ])
2038                .into_array(),
2039                3,
2040                Validity::NonNullable,
2041                4
2042            ),
2043            &mut SESSION.create_execution_ctx()
2044        );
2045        assert_arrays_eq!(
2046            vortex_array_nullable,
2047            VortexFixedSizeListArray::new(
2048                PrimitiveArray::from_option_iter([
2049                    Some(1i32),
2050                    Some(2),
2051                    Some(3),
2052                    Some(4),
2053                    None,
2054                    Some(6),
2055                    Some(7),
2056                    Some(8),
2057                    Some(9)
2058                ])
2059                .into_array(),
2060                3,
2061                Validity::from_iter([true, false, true]),
2062                3
2063            ),
2064            &mut SESSION.create_execution_ctx()
2065        );
2066    }
2067
2068    #[test]
2069    fn test_list_view_array_conversion() {
2070        let mut ctx = SESSION.create_execution_ctx();
2071        // Create values array for the lists
2072        let values = Int32Array::from(vec![
2073            Some(1),
2074            Some(2),
2075            Some(3), // First list [1, 2, 3]
2076            Some(4),
2077            Some(5), // Second list [4, 5]
2078            Some(6), // Third list [6]
2079            Some(7),
2080            Some(8),
2081            Some(9),
2082            Some(10), // Fourth list [7, 8, 9, 10]
2083        ]);
2084
2085        // Create offsets and sizes for ListView
2086        let offsets = ScalarBuffer::from(vec![0i32, 3, 5, 6]);
2087        let sizes = ScalarBuffer::from(vec![3i32, 2, 1, 4]);
2088
2089        let field = Arc::new(Field::new("item", DataType::Int32, true));
2090        let arrow_array = GenericListViewArray::try_new(
2091            Arc::clone(&field),
2092            offsets.clone(),
2093            sizes.clone(),
2094            Arc::new(values.clone()),
2095            None,
2096        )
2097        .unwrap();
2098
2099        let vortex_array = from_arrow_dyn(&arrow_array, false).unwrap();
2100        assert_eq!(vortex_array.len(), 4);
2101
2102        // Verify metadata - should be ListViewArray with correct offsets and sizes
2103        let list_view_vortex_array = vortex_array.as_::<ListView>();
2104        let offsets_array = list_view_vortex_array.offsets().as_::<Primitive>();
2105        let sizes_array = list_view_vortex_array.sizes().as_::<Primitive>();
2106
2107        assert_eq!(offsets_array.len(), 4);
2108        assert_eq!(offsets_array.ptype(), PType::I32);
2109        assert_eq!(sizes_array.len(), 4);
2110        assert_eq!(sizes_array.ptype(), PType::I32);
2111
2112        // Test nullable ListView
2113        let null_buffer = NullBuffer::new(BooleanBuffer::from(vec![true, false, true, true]));
2114
2115        let arrow_array_nullable = GenericListViewArray::try_new(
2116            Arc::clone(&field),
2117            offsets,
2118            sizes,
2119            Arc::new(values.clone()),
2120            Some(null_buffer),
2121        )
2122        .unwrap();
2123
2124        let vortex_array_nullable = from_arrow_dyn(&arrow_array_nullable, true).unwrap();
2125        assert_eq!(vortex_array_nullable.len(), 4);
2126
2127        // Test LargeListView (i64 offsets and sizes)
2128        let large_offsets = ScalarBuffer::from(vec![0i64, 3, 5, 6]);
2129        let large_sizes = ScalarBuffer::from(vec![3i64, 2, 1, 4]);
2130
2131        let large_arrow_array = GenericListViewArray::try_new(
2132            field,
2133            large_offsets,
2134            large_sizes,
2135            Arc::new(values),
2136            None,
2137        )
2138        .unwrap();
2139
2140        let large_vortex_array = from_arrow_dyn(&large_arrow_array, false).unwrap();
2141        assert_eq!(large_vortex_array.len(), 4);
2142
2143        // Verify metadata for large ListView
2144        let large_list_view_vortex_array = large_vortex_array.as_::<ListView>();
2145        let large_offsets_array = large_list_view_vortex_array.offsets().as_::<Primitive>();
2146        let large_sizes_array = large_list_view_vortex_array.sizes().as_::<Primitive>();
2147
2148        assert_eq!(large_offsets_array.len(), 4);
2149        assert_eq!(large_offsets_array.ptype(), PType::I64); // Large ListView uses I64 offsets
2150        assert_eq!(large_sizes_array.len(), 4);
2151        assert_eq!(large_sizes_array.ptype(), PType::I64); // Large ListView uses I64 sizes
2152        let mut expected = |validity| {
2153            ListViewArray::new(
2154                PrimitiveArray::from_option_iter((1i32..=10).map(Some)).into_array(),
2155                buffer![0u32, 3, 5, 6].into_array(),
2156                buffer![3u32, 2, 1, 4].into_array(),
2157                validity,
2158                &mut ctx,
2159            )
2160        };
2161        assert_arrays_eq!(
2162            vortex_array,
2163            expected(Validity::NonNullable),
2164            &mut SESSION.create_execution_ctx()
2165        );
2166        assert_arrays_eq!(
2167            vortex_array_nullable,
2168            expected(Validity::from_iter([true, false, true, true])),
2169            &mut SESSION.create_execution_ctx()
2170        );
2171        assert_arrays_eq!(
2172            large_vortex_array,
2173            expected(Validity::NonNullable),
2174            &mut SESSION.create_execution_ctx()
2175        );
2176    }
2177
2178    // Test null array conversions
2179    #[test]
2180    fn test_null_array_conversion() {
2181        let arrow_array = NullArray::new(5);
2182        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
2183        assert_eq!(vortex_array.len(), 5);
2184        assert_arrays_eq!(
2185            vortex_array,
2186            VortexNullArray::new(5),
2187            &mut SESSION.create_execution_ctx()
2188        );
2189    }
2190
2191    // Test buffer conversions
2192    #[test]
2193    fn test_arrow_buffer_conversion() {
2194        let data = vec![1u8, 2, 3, 4, 5];
2195        let arrow_buffer = ArrowBuffer::from_vec(data);
2196        let vortex_array = arrow_buffer.into_array();
2197        assert_eq!(vortex_array.len(), 5);
2198        assert_arrays_eq!(
2199            vortex_array,
2200            buffer![1u8, 2, 3, 4, 5].into_array(),
2201            &mut SESSION.create_execution_ctx()
2202        );
2203    }
2204
2205    #[test]
2206    fn test_boolean_buffer_conversion() {
2207        let data = vec![true, false, true, false, true];
2208        let boolean_buffer = BooleanBuffer::from(data);
2209        let vortex_array = boolean_buffer.into_array();
2210        assert_eq!(vortex_array.len(), 5);
2211        assert_arrays_eq!(
2212            vortex_array,
2213            BoolArray::from_iter([true, false, true, false, true]),
2214            &mut SESSION.create_execution_ctx()
2215        );
2216    }
2217
2218    #[test]
2219    fn test_scalar_buffer_conversion() {
2220        let data = vec![1i32, 2, 3, 4, 5];
2221        let scalar_buffer = ScalarBuffer::from(data);
2222        let vortex_array = scalar_buffer.into_array();
2223        assert_eq!(vortex_array.len(), 5);
2224        assert_arrays_eq!(
2225            vortex_array,
2226            buffer![1i32, 2, 3, 4, 5].into_array(),
2227            &mut SESSION.create_execution_ctx()
2228        );
2229    }
2230
2231    #[test]
2232    fn test_offset_buffer_conversion() {
2233        let data = vec![0i32, 2, 5, 8, 10];
2234        let offset_buffer = OffsetBuffer::new(ScalarBuffer::from(data));
2235        let vortex_array = offset_buffer.into_array();
2236        assert_eq!(vortex_array.len(), 5);
2237        assert_arrays_eq!(
2238            vortex_array,
2239            buffer![0i32, 2, 5, 8, 10].into_array(),
2240            &mut SESSION.create_execution_ctx()
2241        );
2242    }
2243
2244    // Test RecordBatch conversions
2245    #[test]
2246    fn test_record_batch_conversion() {
2247        let schema = Arc::new(Schema::new(vec![
2248            Field::new("field1", DataType::Int32, false),
2249            Field::new("field2", DataType::Utf8, false),
2250        ]));
2251
2252        let field1_data = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
2253        let field2_data = Arc::new(StringArray::from(vec!["a", "b", "c", "d"]));
2254
2255        let record_batch = RecordBatch::try_new(schema, vec![field1_data, field2_data]).unwrap();
2256
2257        let vortex_array = from_arrow_batch(&record_batch, false).unwrap();
2258        let expected = VortexStructArray::new(
2259            ["field1", "field2"].into(),
2260            vec![
2261                buffer![1i32, 2, 3, 4].into_array(),
2262                VarBinArray::from_iter_nonnull(
2263                    ["a", "b", "c", "d"],
2264                    DType::Utf8(Nullability::NonNullable),
2265                )
2266                .into_array(),
2267            ],
2268            4,
2269            Validity::NonNullable,
2270        );
2271        assert_arrays_eq!(vortex_array, expected, &mut SESSION.create_execution_ctx());
2272
2273        // Test with reference
2274        let schema = Arc::new(Schema::new(vec![
2275            Field::new("field1", DataType::Int32, false),
2276            Field::new("field2", DataType::Utf8, false),
2277        ]));
2278
2279        let field1_data = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
2280        let field2_data = Arc::new(StringArray::from(vec!["a", "b", "c", "d"]));
2281
2282        let record_batch = RecordBatch::try_new(schema, vec![field1_data, field2_data]).unwrap();
2283
2284        let vortex_array = from_arrow_batch(&record_batch, false).unwrap();
2285        let expected = VortexStructArray::new(
2286            ["field1", "field2"].into(),
2287            vec![
2288                buffer![1i32, 2, 3, 4].into_array(),
2289                VarBinArray::from_iter_nonnull(
2290                    ["a", "b", "c", "d"],
2291                    DType::Utf8(Nullability::NonNullable),
2292                )
2293                .into_array(),
2294            ],
2295            4,
2296            Validity::NonNullable,
2297        );
2298        assert_arrays_eq!(vortex_array, expected, &mut SESSION.create_execution_ctx());
2299    }
2300
2301    // Test dynamic dispatch conversion
2302    #[test]
2303    fn test_dyn_array_conversion() {
2304        let int_array = Int32Array::from(vec![1, 2, 3, 4]);
2305        let dyn_array: &dyn ArrowArray = &int_array;
2306        let vortex_array = from_arrow_dyn(dyn_array, false).unwrap();
2307        assert_arrays_eq!(
2308            vortex_array,
2309            buffer![1i32, 2, 3, 4].into_array(),
2310            &mut SESSION.create_execution_ctx()
2311        );
2312
2313        let string_array = StringArray::from(vec!["a", "b", "c"]);
2314        let dyn_array: &dyn ArrowArray = &string_array;
2315        let vortex_array = from_arrow_dyn(dyn_array, false).unwrap();
2316        assert_arrays_eq!(
2317            vortex_array,
2318            VarBinArray::from_iter_nonnull(["a", "b", "c"], DType::Utf8(Nullability::NonNullable)),
2319            &mut SESSION.create_execution_ctx()
2320        );
2321
2322        let bool_array = BooleanArray::from(vec![true, false, true]);
2323        let dyn_array: &dyn ArrowArray = &bool_array;
2324        let vortex_array = from_arrow_dyn(dyn_array, false).unwrap();
2325        assert_arrays_eq!(
2326            vortex_array,
2327            BoolArray::from_iter([true, false, true]),
2328            &mut SESSION.create_execution_ctx()
2329        );
2330    }
2331
2332    // Existing tests
2333    #[test]
2334    pub fn nullable_may_contain_non_nullable() {
2335        let null_struct_array_with_non_nullable_field = new_null_array(
2336            &DataType::Struct(Fields::from(vec![Field::new(
2337                "non_nullable_inner",
2338                DataType::Int32,
2339                false,
2340            )])),
2341            1,
2342        );
2343        let actual =
2344            from_arrow_dyn(null_struct_array_with_non_nullable_field.as_ref(), true).unwrap();
2345        assert_arrays_eq!(
2346            actual,
2347            VortexStructArray::new(
2348                ["non_nullable_inner"].into(),
2349                vec![buffer![0i32].into_array()],
2350                1,
2351                Validity::AllInvalid
2352            ),
2353            &mut SESSION.create_execution_ctx()
2354        );
2355    }
2356
2357    #[test]
2358    pub fn nullable_may_contain_deeply_nested_non_nullable() {
2359        let null_struct_array_with_non_nullable_field = new_null_array(
2360            &DataType::Struct(Fields::from(vec![Field::new(
2361                "non_nullable_inner",
2362                DataType::Struct(Fields::from(vec![Field::new(
2363                    "non_nullable_deeper_inner",
2364                    DataType::Int32,
2365                    false,
2366                )])),
2367                false,
2368            )])),
2369            1,
2370        );
2371        let actual =
2372            from_arrow_dyn(null_struct_array_with_non_nullable_field.as_ref(), true).unwrap();
2373        assert_arrays_eq!(
2374            actual,
2375            VortexStructArray::new(
2376                ["non_nullable_inner"].into(),
2377                vec![
2378                    VortexStructArray::new(
2379                        ["non_nullable_deeper_inner"].into(),
2380                        vec![buffer![0i32].into_array()],
2381                        1,
2382                        Validity::NonNullable
2383                    )
2384                    .into_array()
2385                ],
2386                1,
2387                Validity::AllInvalid
2388            ),
2389            &mut SESSION.create_execution_ctx()
2390        );
2391    }
2392
2393    #[test]
2394    fn dyn_dispatch_imports_map() -> VortexResult<()> {
2395        let mut builder = ArrowMapBuilder::new(None, StringBuilder::new(), Int32Builder::new());
2396        builder.keys().append_value("joe");
2397        builder.values().append_value(1);
2398        builder.append(true)?;
2399        builder.append(false)?;
2400        let arrow = builder.finish();
2401
2402        let expected = DType::map(
2403            DType::Utf8(Nullability::NonNullable),
2404            DType::Primitive(PType::I32, Nullability::Nullable),
2405            false,
2406            Nullability::Nullable,
2407        )?;
2408
2409        // Dispatching on the Arrow data type must cover maps...
2410        let direct = from_arrow_dyn(&arrow, true)?;
2411        assert_eq!(direct.dtype(), &expected);
2412
2413        // ...including maps reached by recursing into a container.
2414        let batch = RecordBatch::try_from_iter_with_nullable([(
2415            "maps",
2416            Arc::new(arrow) as Arc<dyn ArrowArray>,
2417            true,
2418        )])?;
2419        let imported = from_arrow_batch(&batch, false)?;
2420        assert_eq!(
2421            imported.as_::<Struct>().unmasked_field(0).dtype(),
2422            &expected
2423        );
2424
2425        let row = Scalar::try_map(
2426            expected.clone(),
2427            [(
2428                Scalar::utf8("joe", Nullability::NonNullable),
2429                Scalar::primitive(1i32, Nullability::Nullable),
2430            )],
2431        )?;
2432        let mut ctx = SESSION.create_execution_ctx();
2433        for actual in [&direct, imported.as_::<Struct>().unmasked_field(0)] {
2434            assert_eq!(actual.len(), 2);
2435            assert_eq!(actual.execute_scalar(0, &mut ctx)?, row);
2436            assert_eq!(
2437                actual.execute_scalar(1, &mut ctx)?,
2438                Scalar::null(expected.clone())
2439            );
2440        }
2441        Ok(())
2442    }
2443
2444    #[test]
2445    fn non_nullable_request_rejects_nulls() {
2446        // Requesting `nullable = false` on an Arrow array that physically contains nulls is a
2447        // contradiction and must surface as an error, not a panic.
2448        let arrow_array = Int32Array::from(vec![Some(1), None, Some(3)]);
2449        assert!(from_arrow_dyn(&arrow_array, false).is_err());
2450    }
2451
2452    #[test]
2453    fn non_nullable_request_rejects_null_array() {
2454        // An Arrow NullArray is entirely null, so it cannot be converted to a non-nullable
2455        // Vortex array.
2456        let arrow_array = NullArray::new(5);
2457        assert!(from_arrow_dyn(&arrow_array, false).is_err());
2458    }
2459
2460    #[test]
2461    fn non_nullable_struct_with_nulls_errors() {
2462        // A struct array carrying top-level nulls cannot be converted to a non-nullable Vortex
2463        // struct; the struct-level validity reconciliation must error rather than panic.
2464        let struct_array = new_null_array(
2465            &DataType::Struct(Fields::from(vec![Field::new("a", DataType::Int32, true)])),
2466            3,
2467        );
2468        assert!(from_arrow_dyn(struct_array.as_ref(), false).is_err());
2469    }
2470
2471    #[test]
2472    fn non_nullable_list_with_nulls_errors() {
2473        // Likewise for a list array with a null entry: requesting a non-nullable list must error
2474        // rather than panic.
2475        let mut builder = ListBuilder::new(Int32Builder::new());
2476        builder.append_value([Some(1), Some(2)]);
2477        builder.append_null();
2478        let list = builder.finish();
2479        assert!(from_arrow_dyn(&list, false).is_err());
2480    }
2481
2482    #[test]
2483    pub fn nullable_struct_containing_non_nullable_dictionary_with_nulls_errors() {
2484        // `remove_nulls` cannot strip pushed-down nulls out of a non-nullable dictionary field,
2485        // so the values end up converted with `nullable = false` while still containing nulls.
2486        // This must surface as an error rather than panicking.
2487        let null_struct_array_with_non_nullable_field = new_null_array(
2488            &DataType::Struct(Fields::from(vec![Field::new(
2489                "non_nullable_deeper_inner",
2490                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
2491                false,
2492            )])),
2493            1,
2494        );
2495
2496        assert!(from_arrow_dyn(null_struct_array_with_non_nullable_field.as_ref(), true).is_err());
2497    }
2498}