|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | +// SPDX-FileCopyrightText: Copyright the Vortex contributors |
| 3 | + |
| 4 | +use std::sync::Arc; |
| 5 | + |
| 6 | +use arrow_array::ArrayRef as ArrowArrayRef; |
| 7 | +use arrow_array::GenericBinaryArray; |
| 8 | +use arrow_array::types::ByteArrayType; |
| 9 | +use vortex_compute::arrow::IntoArrow; |
| 10 | +use vortex_dtype::DType; |
| 11 | +use vortex_dtype::NativePType; |
| 12 | +use vortex_dtype::Nullability; |
| 13 | +use vortex_dtype::PTypeDowncastExt; |
| 14 | +use vortex_error::VortexError; |
| 15 | +use vortex_error::VortexResult; |
| 16 | +use vortex_session::VortexSession; |
| 17 | + |
| 18 | +use crate::ArrayRef; |
| 19 | +use crate::VectorExecutor; |
| 20 | +use crate::arrays::VarBinArray; |
| 21 | +use crate::arrays::VarBinVTable; |
| 22 | +use crate::arrow::null_buffer::to_null_buffer; |
| 23 | +use crate::builtins::ArrayBuiltins; |
| 24 | + |
| 25 | +/// Convert a Vortex array into an Arrow GenericBinaryArray. |
| 26 | +pub(super) fn to_arrow_byte_array<T: ByteArrayType>( |
| 27 | + array: ArrayRef, |
| 28 | + session: &VortexSession, |
| 29 | +) -> VortexResult<ArrowArrayRef> |
| 30 | +where |
| 31 | + T::Offset: NativePType, |
| 32 | +{ |
| 33 | + // If the Vortex array is already in VarBin format, we can directly convert it. |
| 34 | + if let Some(array) = array.as_opt::<VarBinVTable>() { |
| 35 | + return varbin_to_byte_array::<T>(array, session); |
| 36 | + } |
| 37 | + |
| 38 | + // Otherwise, we execute the array to a BinaryView vector and cast from there. |
| 39 | + let binary_view = array.execute_vector(session)?.into_arrow()?; |
| 40 | + arrow_cast::cast(&binary_view, &T::DATA_TYPE).map_err(VortexError::from) |
| 41 | +} |
| 42 | + |
| 43 | +/// Convert a Vortex VarBinArray into an Arrow GenericBinaryArray. |
| 44 | +fn varbin_to_byte_array<T: ByteArrayType>( |
| 45 | + array: &VarBinArray, |
| 46 | + session: &VortexSession, |
| 47 | +) -> VortexResult<ArrowArrayRef> |
| 48 | +where |
| 49 | + T::Offset: NativePType, |
| 50 | +{ |
| 51 | + // We must cast the offsets to the required offset type. |
| 52 | + let offsets = array |
| 53 | + .offsets() |
| 54 | + .cast(DType::Primitive(T::Offset::PTYPE, Nullability::NonNullable))? |
| 55 | + .execute_vector(session)? |
| 56 | + .into_primitive() |
| 57 | + .downcast::<T::Offset>() |
| 58 | + .into_buffer() |
| 59 | + .into_arrow_offset_buffer(); |
| 60 | + |
| 61 | + let data = array.bytes().clone().into_arrow_buffer(); |
| 62 | + |
| 63 | + let null_buffer = to_null_buffer(array.validity_mask()); |
| 64 | + |
| 65 | + Ok(Arc::new(unsafe { |
| 66 | + GenericBinaryArray::<T::Offset>::new_unchecked(offsets, data, null_buffer) |
| 67 | + })) |
| 68 | +} |
0 commit comments