datafusion_spark/function/string/
char.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use 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/// Spark-compatible `char` expression
31/// <https://spark.apache.org/docs/latest/api/sql/index.html#char>
32#[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
73/// Returns the ASCII character having the binary equivalent to the input expression.
74/// E.g., chr(65) = 'A'.
75/// Compatible with Apache Spark's Chr function
76fn 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(""); // empty string for negative numbers.
116                } 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}