datafusion_functions/string/
to_hex.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 std::any::Any;
19use std::fmt::Write;
20use std::sync::Arc;
21
22use arrow::array::{ArrayRef, GenericStringBuilder, OffsetSizeTrait};
23use arrow::datatypes::{
24    ArrowNativeType, ArrowPrimitiveType, DataType, Int32Type, Int64Type,
25};
26
27use crate::utils::make_scalar_function;
28use datafusion_common::cast::as_primitive_array;
29use datafusion_common::Result;
30use datafusion_common::{exec_err, plan_err};
31
32use datafusion_expr::{ColumnarValue, Documentation};
33use datafusion_expr::{ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility};
34use datafusion_macros::user_doc;
35
36/// Converts the number to its equivalent hexadecimal representation.
37/// to_hex(2147483647) = '7fffffff'
38pub fn to_hex<T: ArrowPrimitiveType>(args: &[ArrayRef]) -> Result<ArrayRef>
39where
40    T::Native: OffsetSizeTrait,
41{
42    let integer_array = as_primitive_array::<T>(&args[0])?;
43
44    let mut result = GenericStringBuilder::<i32>::with_capacity(
45        integer_array.len(),
46        // * 8 to convert to bits, / 4 bits per hex char
47        integer_array.len() * (T::Native::get_byte_width() * 8 / 4),
48    );
49
50    for integer in integer_array {
51        if let Some(value) = integer {
52            if let Some(value_usize) = value.to_usize() {
53                write!(result, "{value_usize:x}")?;
54            } else if let Some(value_isize) = value.to_isize() {
55                write!(result, "{value_isize:x}")?;
56            } else {
57                return exec_err!(
58                    "Unsupported data type {integer:?} for function to_hex"
59                );
60            }
61            result.append_value("");
62        } else {
63            result.append_null();
64        }
65    }
66
67    let result = result.finish();
68
69    Ok(Arc::new(result) as ArrayRef)
70}
71
72#[user_doc(
73    doc_section(label = "String Functions"),
74    description = "Converts an integer to a hexadecimal string.",
75    syntax_example = "to_hex(int)",
76    sql_example = r#"```sql
77> select to_hex(12345689);
78+-------------------------+
79| to_hex(Int64(12345689)) |
80+-------------------------+
81| bc6159                  |
82+-------------------------+
83```"#,
84    standard_argument(name = "int", prefix = "Integer")
85)]
86#[derive(Debug)]
87pub struct ToHexFunc {
88    signature: Signature,
89}
90
91impl Default for ToHexFunc {
92    fn default() -> Self {
93        Self::new()
94    }
95}
96
97impl ToHexFunc {
98    pub fn new() -> Self {
99        use DataType::*;
100        Self {
101            signature: Signature::uniform(1, vec![Int64], Volatility::Immutable),
102        }
103    }
104}
105
106impl ScalarUDFImpl for ToHexFunc {
107    fn as_any(&self) -> &dyn Any {
108        self
109    }
110
111    fn name(&self) -> &str {
112        "to_hex"
113    }
114
115    fn signature(&self) -> &Signature {
116        &self.signature
117    }
118
119    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
120        use DataType::*;
121
122        Ok(match arg_types[0] {
123            Int8 | Int16 | Int32 | Int64 => Utf8,
124            _ => {
125                return plan_err!("The to_hex function can only accept integers.");
126            }
127        })
128    }
129
130    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
131        match args.args[0].data_type() {
132            DataType::Int32 => {
133                make_scalar_function(to_hex::<Int32Type>, vec![])(&args.args)
134            }
135            DataType::Int64 => {
136                make_scalar_function(to_hex::<Int64Type>, vec![])(&args.args)
137            }
138            other => exec_err!("Unsupported data type {other:?} for function to_hex"),
139        }
140    }
141
142    fn documentation(&self) -> Option<&Documentation> {
143        self.doc()
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use arrow::array::{Int32Array, StringArray};
150
151    use datafusion_common::cast::as_string_array;
152
153    use super::*;
154
155    #[test]
156    // Test to_hex function for zero
157    fn to_hex_zero() -> Result<()> {
158        let array = vec![0].into_iter().collect::<Int32Array>();
159        let array_ref = Arc::new(array);
160        let hex_value_arc = to_hex::<Int32Type>(&[array_ref])?;
161        let hex_value = as_string_array(&hex_value_arc)?;
162        let expected = StringArray::from(vec![Some("0")]);
163        assert_eq!(&expected, hex_value);
164
165        Ok(())
166    }
167
168    #[test]
169    // Test to_hex function for positive number
170    fn to_hex_positive_number() -> Result<()> {
171        let array = vec![100].into_iter().collect::<Int32Array>();
172        let array_ref = Arc::new(array);
173        let hex_value_arc = to_hex::<Int32Type>(&[array_ref])?;
174        let hex_value = as_string_array(&hex_value_arc)?;
175        let expected = StringArray::from(vec![Some("64")]);
176        assert_eq!(&expected, hex_value);
177
178        Ok(())
179    }
180
181    #[test]
182    // Test to_hex function for negative number
183    fn to_hex_negative_number() -> Result<()> {
184        let array = vec![-1].into_iter().collect::<Int32Array>();
185        let array_ref = Arc::new(array);
186        let hex_value_arc = to_hex::<Int32Type>(&[array_ref])?;
187        let hex_value = as_string_array(&hex_value_arc)?;
188        let expected = StringArray::from(vec![Some("ffffffffffffffff")]);
189        assert_eq!(&expected, hex_value);
190
191        Ok(())
192    }
193}