Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Casting generic binary to generic string #3607

Merged
merged 3 commits into from
Jan 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 78 additions & 51 deletions arrow-cast/src/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,8 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool {

(Utf8, LargeUtf8) => true,
(LargeUtf8, Utf8) => true,
(Binary, LargeBinary) => true,
(LargeBinary, Binary) => true,
(Binary, LargeBinary | Utf8 | LargeUtf8) => true,
(LargeBinary, Binary | Utf8 | LargeUtf8) => true,
(Utf8,
Binary
| LargeBinary
Expand Down Expand Up @@ -185,7 +185,7 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool {
(Timestamp(_, _), Utf8) | (Timestamp(_, _), LargeUtf8) => true,
(Date32, Utf8) | (Date32, LargeUtf8) => true,
(Date64, Utf8) | (Date64, LargeUtf8) => true,
(_, Utf8 | LargeUtf8) => (DataType::is_numeric(from_type) && from_type != &Float16) || from_type == &Binary,
(_, Utf8 | LargeUtf8) => DataType::is_numeric(from_type) && from_type != &Float16,

// start numeric casts
(
Expand Down Expand Up @@ -1180,30 +1180,8 @@ pub fn cast_with_options(
}
Date32 => cast_date32_to_string::<i32>(array),
Date64 => cast_date64_to_string::<i32>(array),
Binary => {
let array = array.as_any().downcast_ref::<BinaryArray>().unwrap();
Ok(Arc::new(
array
.iter()
.map(|maybe_value| match maybe_value {
Some(value) => {
let result = std::str::from_utf8(value);
if cast_options.safe {
Ok(result.ok())
} else {
Some(result.map_err(|_| {
ArrowError::CastError(
"Cannot cast binary to string".to_string(),
)
}))
.transpose()
}
}
None => Ok(None),
})
.collect::<Result<StringArray, _>>()?,
))
}
Binary => cast_binary_to_generic_string::<i32, i32>(array, cast_options),
LargeBinary => cast_binary_to_generic_string::<i64, i32>(array, cast_options),
_ => Err(ArrowError::CastError(format!(
"Casting from {from_type:?} to {to_type:?} not supported",
))),
Expand Down Expand Up @@ -1236,30 +1214,8 @@ pub fn cast_with_options(
}
Date32 => cast_date32_to_string::<i64>(array),
Date64 => cast_date64_to_string::<i64>(array),
Binary => {
let array = array.as_any().downcast_ref::<BinaryArray>().unwrap();
Ok(Arc::new(
array
.iter()
.map(|maybe_value| match maybe_value {
Some(value) => {
let result = std::str::from_utf8(value);
if cast_options.safe {
Ok(result.ok())
} else {
Some(result.map_err(|_| {
ArrowError::CastError(
"Cannot cast binary to string".to_string(),
)
}))
.transpose()
}
}
None => Ok(None),
})
.collect::<Result<LargeStringArray, _>>()?,
))
}
Binary => cast_binary_to_generic_string::<i32, i64>(array, cast_options),
LargeBinary => cast_binary_to_generic_string::<i64, i64>(array, cast_options),
_ => Err(ArrowError::CastError(format!(
"Casting from {from_type:?} to {to_type:?} not supported",
))),
Expand Down Expand Up @@ -3436,6 +3392,77 @@ fn cast_list_inner<OffsetSize: OffsetSizeTrait>(
Ok(Arc::new(list) as ArrayRef)
}

/// Helper function to cast from `GenericBinaryArray` to `GenericStringArray`. This function performs
/// UTF8 validation during casting. For invalid UTF8 value, it could be Null or returning `Err` depending
/// `CastOptions`.
fn cast_binary_to_generic_string<I, O>(
array: &dyn Array,
cast_options: &CastOptions,
) -> Result<ArrayRef, ArrowError>
where
I: OffsetSizeTrait + ToPrimitive,
O: OffsetSizeTrait + NumCast,
{
let array = array
.as_any()
.downcast_ref::<GenericByteArray<GenericBinaryType<I>>>()
.unwrap();

if !cast_options.safe {
let offsets = array.value_offsets();
let values = array.value_data();

// We only need to validate that all values are valid UTF-8
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems a shame to duplicate this logic, but I guess it is hard to avoid whilst having this type signature

let validated = std::str::from_utf8(values)
.map_err(|_| ArrowError::CastError("Invalid UTF-8 sequence".to_string()))?;

let mut offset_builder = BufferBuilder::<O>::new(offsets.len());
offsets
.iter()
.try_for_each::<_, Result<_, ArrowError>>(|offset| {
if !validated.is_char_boundary(offset.as_usize()) {
return Err(ArrowError::CastError(
"Invalid UTF-8 sequence".to_string(),
));
}

let offset = <O as NumCast>::from(*offset).ok_or_else(|| {
ArrowError::ComputeError(format!(
"{}Binary array too large to cast to {}String array",
I::PREFIX,
O::PREFIX
))
})?;
offset_builder.append(offset);
Ok(())
})?;

let offset_buffer = offset_builder.finish();

let builder = ArrayData::builder(GenericStringArray::<O>::DATA_TYPE)
viirya marked this conversation as resolved.
Show resolved Hide resolved
.len(array.len())
.add_buffer(offset_buffer)
.add_buffer(array.data().buffers()[1].clone())
.null_count(array.null_count())
.null_bit_buffer(array.data().null_buffer().cloned());

// SAFETY:
// Validated UTF-8 above
Ok(Arc::new(GenericStringArray::<O>::from(unsafe {
builder.build_unchecked()
})))
} else {
Ok(Arc::new(
array
.iter()
.map(|maybe_value| {
maybe_value.and_then(|value| std::str::from_utf8(value).ok())
})
.collect::<GenericByteArray<GenericStringType<O>>>(),
))
}
}

/// Helper function to cast from one `ByteArrayType` to another and vice versa.
/// If the target one (e.g., `LargeUtf8`) is too large for the source array it will return an Error.
fn cast_byte_container<FROM, TO, N: ?Sized>(
Expand Down