1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// start implementing uses
use arrow::array::{ArrayRef, GenericStringArray};
use arrow::datatypes::DataType;
use datafusion::common::cast::as_binary_array;
use datafusion::common::Result;
use datafusion::logical_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
use std::any::Any;
use std::sync::Arc;

use crate::utils::make_scalar_function;

// end implementing uses

#[derive(Debug)]
pub(super) struct Func {
    signature: Signature,
}

impl Func {
    pub fn new() -> Self {        
        // start implementing constructor
        Self {
            signature: Signature::exact(vec![DataType::Binary], Volatility::Immutable),
        }
        // end implementing constructor
    }
}

impl ScalarUDFImpl for Func {
    fn as_any(&self) -> &dyn Any {
        self
    }
    fn name(&self) -> &str {
        "to_hex"
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    // start implementing return_type
    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
        Ok(DataType::Utf8)
    }
    // end implementing return_type

    // start implementing invoke
    fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
        make_scalar_function(to_hex, vec![])(args)
    }
    // end implementing invoke
}

// start implementing footer
fn to_hex(args: &[ArrayRef]) -> Result<ArrayRef> {
    let binary_array = as_binary_array(&args[0])?;
    let result = binary_array
        .iter()
        .map(|binary| {
            let hex = binary.map(|binary| {
                let hex = binary
                    .iter()
                    .map(|byte| format!("{:02x}", byte))
                    .collect::<String>();
                hex
            });
            Ok(hex)
        })
        .collect::<Result<GenericStringArray<i32>>>()?;
    Ok(Arc::new(result) as ArrayRef)
}
 
// end implementing footer