Skip to content

Optimize char expression #16076

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
39 changes: 20 additions & 19 deletions datafusion/spark/src/function/string/char.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
use std::{any::Any, sync::Arc};

use arrow::{
array::{ArrayRef, StringArray},
array::{ArrayRef, GenericStringBuilder},
datatypes::{
DataType,
DataType::{Int64, Utf8},
Expand Down Expand Up @@ -106,25 +106,26 @@ fn spark_chr(args: &[ColumnarValue]) -> Result<ColumnarValue> {
fn chr(args: &[ArrayRef]) -> Result<ArrayRef> {
let integer_array = as_int64_array(&args[0])?;

// first map is the iterator, second is for the `Option<_>`
let result = integer_array
.iter()
.map(|integer: Option<i64>| {
integer
.map(|integer| {
if integer < 0 {
return Ok("".to_string()); // Return empty string for negative integers
}
let mut builder = GenericStringBuilder::<i32>::with_capacity(
integer_array.len(),
integer_array.len(),
);

for integer_opt in integer_array {
match integer_opt {
Some(integer) => {
if integer < 0 {
builder.append_value(""); // empty string for negative numbers.
} else {
match core::char::from_u32((integer % 256) as u32) {
Some(ch) => Ok(ch.to_string()),
None => {
exec_err!("requested character not compatible for encoding.")
}
Some(ch) => builder.append_value(ch.to_string()),
None => return exec_err!("requested character not compatible for encoding.")
}
})
.transpose()
})
.collect::<Result<StringArray>>()?;
}
}
None => builder.append_null(),
}
}

Ok(Arc::new(result) as ArrayRef)
Ok(Arc::new(builder.finish()) as ArrayRef)
}