Skip to main content

datafusion_spark/function/math/
bin.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, AsArray, StringArray};
19use arrow::datatypes::{DataType, Field, FieldRef, Int64Type};
20use datafusion_common::types::{NativeType, logical_int64};
21use datafusion_common::utils::take_function_args;
22use datafusion_common::{Result, internal_err};
23use datafusion_expr::{
24    Coercion, ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature,
25    TypeSignatureClass, Volatility,
26};
27use datafusion_functions::utils::make_scalar_function;
28use std::sync::Arc;
29
30/// Spark-compatible `bin` expression
31/// <https://spark.apache.org/docs/latest/api/sql/index.html#bin>
32#[derive(Debug, PartialEq, Eq, Hash)]
33pub struct SparkBin {
34    signature: Signature,
35}
36
37impl Default for SparkBin {
38    fn default() -> Self {
39        Self::new()
40    }
41}
42
43impl SparkBin {
44    pub fn new() -> Self {
45        Self {
46            signature: Signature::one_of(
47                vec![TypeSignature::Coercible(vec![Coercion::new_implicit(
48                    TypeSignatureClass::Native(logical_int64()),
49                    vec![TypeSignatureClass::Numeric],
50                    NativeType::Int64,
51                )])],
52                Volatility::Immutable,
53            ),
54        }
55    }
56}
57
58impl ScalarUDFImpl for SparkBin {
59    fn name(&self) -> &str {
60        "bin"
61    }
62
63    fn signature(&self) -> &Signature {
64        &self.signature
65    }
66
67    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
68        internal_err!("return_field_from_args should be used instead")
69    }
70
71    fn return_field_from_args(
72        &self,
73        args: datafusion_expr::ReturnFieldArgs,
74    ) -> Result<FieldRef> {
75        Ok(Arc::new(Field::new(
76            self.name(),
77            DataType::Utf8,
78            args.arg_fields[0].is_nullable(),
79        )))
80    }
81
82    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
83        make_scalar_function(spark_bin_inner, vec![])(&args.args)
84    }
85}
86
87fn spark_bin_inner(arg: &[ArrayRef]) -> Result<ArrayRef> {
88    let [array] = take_function_args("bin", arg)?;
89    match &array.data_type() {
90        DataType::Int64 => {
91            let result: StringArray = array
92                .as_primitive::<Int64Type>()
93                .iter()
94                .map(|opt| opt.map(spark_bin))
95                .collect();
96            Ok(Arc::new(result))
97        }
98        data_type => {
99            internal_err!("bin does not support: {data_type}")
100        }
101    }
102}
103
104fn spark_bin(value: i64) -> String {
105    format!("{value:b}")
106}