datafusion_spark/function/string/
char.rs1use arrow::array::ArrayRef;
19use arrow::array::GenericStringBuilder;
20use arrow::datatypes::DataType;
21use arrow::datatypes::DataType::Int64;
22use arrow::datatypes::DataType::Utf8;
23use std::{any::Any, sync::Arc};
24
25use datafusion_common::{cast::as_int64_array, exec_err, Result, ScalarValue};
26use datafusion_expr::{
27 ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
28};
29
30#[derive(Debug, PartialEq, Eq, Hash)]
33pub struct CharFunc {
34 signature: Signature,
35}
36
37impl Default for CharFunc {
38 fn default() -> Self {
39 Self::new()
40 }
41}
42
43impl CharFunc {
44 pub fn new() -> Self {
45 Self {
46 signature: Signature::uniform(1, vec![Int64], Volatility::Immutable),
47 }
48 }
49}
50
51impl ScalarUDFImpl for CharFunc {
52 fn as_any(&self) -> &dyn Any {
53 self
54 }
55
56 fn name(&self) -> &str {
57 "char"
58 }
59
60 fn signature(&self) -> &Signature {
61 &self.signature
62 }
63
64 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
65 Ok(Utf8)
66 }
67
68 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
69 spark_chr(&args.args)
70 }
71}
72
73fn spark_chr(args: &[ColumnarValue]) -> Result<ColumnarValue> {
77 let array = args[0].clone();
78 match array {
79 ColumnarValue::Array(array) => {
80 let array = chr(&[array])?;
81 Ok(ColumnarValue::Array(array))
82 }
83 ColumnarValue::Scalar(ScalarValue::Int64(Some(value))) => {
84 if value < 0 {
85 Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some(
86 "".to_string(),
87 ))))
88 } else {
89 match core::char::from_u32((value % 256) as u32) {
90 Some(ch) => Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some(
91 ch.to_string(),
92 )))),
93 None => {
94 exec_err!("requested character was incompatible for encoding.")
95 }
96 }
97 }
98 }
99 _ => exec_err!("The argument must be an Int64 array or scalar."),
100 }
101}
102
103fn chr(args: &[ArrayRef]) -> Result<ArrayRef> {
104 let integer_array = as_int64_array(&args[0])?;
105
106 let mut builder = GenericStringBuilder::<i32>::with_capacity(
107 integer_array.len(),
108 integer_array.len(),
109 );
110
111 for integer_opt in integer_array {
112 match integer_opt {
113 Some(integer) => {
114 if integer < 0 {
115 builder.append_value(""); } else {
117 match core::char::from_u32((integer % 256) as u32) {
118 Some(ch) => builder.append_value(ch.to_string()),
119 None => {
120 return exec_err!(
121 "requested character not compatible for encoding."
122 )
123 }
124 }
125 }
126 }
127 None => builder.append_null(),
128 }
129 }
130
131 Ok(Arc::new(builder.finish()) as ArrayRef)
132}