Skip to main content

datafusion_spark/function/bitwise/
bit_get.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::mem::size_of;
20use std::sync::Arc;
21
22use arrow::array::{
23    Array, ArrayRef, ArrowPrimitiveType, AsArray, Int8Array, Int32Array, PrimitiveArray,
24    downcast_integer_array,
25};
26use arrow::compute::try_binary;
27use arrow::datatypes::{ArrowNativeType, DataType, Field, FieldRef, Int8Type, Int32Type};
28use datafusion_common::types::{NativeType, logical_int32};
29use datafusion_common::utils::take_function_args;
30use datafusion_common::{Result, internal_err};
31use datafusion_expr::{
32    Coercion, ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl,
33    Signature, TypeSignatureClass, Volatility,
34};
35use datafusion_functions::utils::make_scalar_function;
36
37#[derive(Debug, PartialEq, Eq, Hash)]
38pub struct SparkBitGet {
39    signature: Signature,
40    aliases: Vec<String>,
41}
42
43impl Default for SparkBitGet {
44    fn default() -> Self {
45        Self::new()
46    }
47}
48
49impl SparkBitGet {
50    pub fn new() -> Self {
51        Self {
52            signature: Signature::coercible(
53                vec![
54                    Coercion::new_exact(TypeSignatureClass::Integer),
55                    Coercion::new_implicit(
56                        TypeSignatureClass::Native(logical_int32()),
57                        vec![TypeSignatureClass::Integer],
58                        NativeType::Int32,
59                    ),
60                ],
61                Volatility::Immutable,
62            ),
63            aliases: vec!["getbit".to_string()],
64        }
65    }
66}
67
68impl ScalarUDFImpl for SparkBitGet {
69    fn as_any(&self) -> &dyn Any {
70        self
71    }
72
73    fn name(&self) -> &str {
74        "bit_get"
75    }
76
77    fn aliases(&self) -> &[String] {
78        &self.aliases
79    }
80
81    fn signature(&self) -> &Signature {
82        &self.signature
83    }
84
85    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
86        internal_err!("return_field_from_args should be used instead")
87    }
88
89    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
90        // Spark derives nullability for BinaryExpression from its children
91        let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
92        Ok(Arc::new(Field::new(self.name(), DataType::Int8, nullable)))
93    }
94
95    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
96        make_scalar_function(spark_bit_get, vec![])(&args.args)
97    }
98}
99
100fn spark_bit_get_inner<T: ArrowPrimitiveType>(
101    value: &PrimitiveArray<T>,
102    pos: &Int32Array,
103) -> Result<Int8Array> {
104    let bit_length = (size_of::<T::Native>() * 8) as i32;
105
106    let result: PrimitiveArray<Int8Type> = try_binary(value, pos, |value, pos| {
107        if pos < 0 || pos >= bit_length {
108            return Err(arrow::error::ArrowError::ComputeError(format!(
109                "bit_get: position {pos} is out of bounds. Expected pos < {bit_length} and pos >= 0"
110            )));
111        }
112        Ok(((value.to_i64().unwrap() >> pos) & 1) as i8)
113    })?;
114    Ok(result)
115}
116
117fn spark_bit_get(args: &[ArrayRef]) -> Result<ArrayRef> {
118    let [value, position] = take_function_args("bit_get", args)?;
119    let pos_arg = position.as_primitive::<Int32Type>();
120    let ret = downcast_integer_array!(
121        value => spark_bit_get_inner(value, pos_arg),
122        DataType::Null => Ok(Int8Array::new_null(value.len())),
123        d => internal_err!("Unsupported datatype for bit_get: {d}"),
124    )?;
125    Ok(Arc::new(ret))
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use arrow::datatypes::Field;
132
133    #[test]
134    fn test_bit_get_nullability_non_nullable_inputs() {
135        let func = SparkBitGet::new();
136        let value_field = Arc::new(Field::new("value", DataType::Int32, false));
137        let pos_field = Arc::new(Field::new("pos", DataType::Int32, false));
138
139        let out_field = func
140            .return_field_from_args(ReturnFieldArgs {
141                arg_fields: &[value_field, pos_field],
142                scalar_arguments: &[None, None],
143            })
144            .unwrap();
145
146        assert_eq!(out_field.data_type(), &DataType::Int8);
147        assert!(!out_field.is_nullable());
148    }
149
150    #[test]
151    fn test_bit_get_nullability_nullable_inputs() {
152        let func = SparkBitGet::new();
153        let value_field = Arc::new(Field::new("value", DataType::Int32, true));
154        let pos_field = Arc::new(Field::new("pos", DataType::Int32, false));
155
156        let out_field = func
157            .return_field_from_args(ReturnFieldArgs {
158                arg_fields: &[value_field, pos_field],
159                scalar_arguments: &[None, None],
160            })
161            .unwrap();
162
163        assert_eq!(out_field.data_type(), &DataType::Int8);
164        assert!(out_field.is_nullable());
165    }
166}