datafusion_functions/string/
to_hex.rs1use 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
36pub 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 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 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 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 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}