datafusion_comet_spark_expr/bitwise_funcs/
bitwise_count.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::*, datatypes::DataType};
19use datafusion::common::{exec_err, internal_datafusion_err, internal_err, Result};
20use datafusion::logical_expr::{ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility};
21use datafusion::{error::DataFusionError, logical_expr::ColumnarValue};
22use std::any::Any;
23use std::sync::Arc;
24
25#[derive(Debug)]
26pub struct SparkBitwiseCount {
27    signature: Signature,
28    aliases: Vec<String>,
29}
30
31impl Default for SparkBitwiseCount {
32    fn default() -> Self {
33        Self::new()
34    }
35}
36
37impl SparkBitwiseCount {
38    pub fn new() -> Self {
39        Self {
40            signature: Signature::user_defined(Volatility::Immutable),
41            aliases: vec![],
42        }
43    }
44}
45
46impl ScalarUDFImpl for SparkBitwiseCount {
47    fn as_any(&self) -> &dyn Any {
48        self
49    }
50
51    fn name(&self) -> &str {
52        "bit_count"
53    }
54
55    fn signature(&self) -> &Signature {
56        &self.signature
57    }
58
59    fn return_type(&self, _: &[DataType]) -> Result<DataType> {
60        Ok(DataType::Int32)
61    }
62
63    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
64        let args: [ColumnarValue; 1] = args
65            .args
66            .try_into()
67            .map_err(|_| internal_datafusion_err!("bit_count expects exactly one argument"))?;
68        spark_bit_count(args)
69    }
70
71    fn aliases(&self) -> &[String] {
72        &self.aliases
73    }
74}
75
76macro_rules! compute_op {
77    ($OPERAND:expr, $DT:ident) => {{
78        let operand = $OPERAND.as_any().downcast_ref::<$DT>().ok_or_else(|| {
79            DataFusionError::Execution(format!(
80                "compute_op failed to downcast array to: {:?}",
81                stringify!($DT)
82            ))
83        })?;
84
85        let result: Int32Array = operand
86            .iter()
87            .map(|x| x.map(|y| bit_count(y.into())))
88            .collect();
89
90        Ok(Arc::new(result))
91    }};
92}
93
94pub fn spark_bit_count(args: [ColumnarValue; 1]) -> Result<ColumnarValue> {
95    match args {
96        [ColumnarValue::Array(array)] => {
97            let result: Result<ArrayRef> = match array.data_type() {
98                DataType::Int8 | DataType::Boolean => compute_op!(array, Int8Array),
99                DataType::Int16 => compute_op!(array, Int16Array),
100                DataType::Int32 => compute_op!(array, Int32Array),
101                DataType::Int64 => compute_op!(array, Int64Array),
102                _ => exec_err!("bit_count can't be evaluated because the expression's type is {:?}, not signed int", array.data_type()),
103            };
104            result.map(ColumnarValue::Array)
105        }
106        [ColumnarValue::Scalar(_)] => internal_err!("shouldn't go to bitwise count scalar path"),
107    }
108}
109
110// Here’s the equivalent Rust implementation of the bitCount function (similar to Apache Spark's bitCount for LongType)
111fn bit_count(i: i64) -> i32 {
112    let mut u = i as u64;
113    u = u - ((u >> 1) & 0x5555555555555555);
114    u = (u & 0x3333333333333333) + ((u >> 2) & 0x3333333333333333);
115    u = (u + (u >> 4)) & 0x0f0f0f0f0f0f0f0f;
116    u = u + (u >> 8);
117    u = u + (u >> 16);
118    u = u + (u >> 32);
119    (u as i32) & 0x7f
120}
121
122#[cfg(test)]
123mod tests {
124    use datafusion::common::{cast::as_int32_array, Result};
125
126    use super::*;
127
128    #[test]
129    fn bitwise_count_op() -> Result<()> {
130        let args = ColumnarValue::Array(Arc::new(Int32Array::from(vec![
131            Some(1),
132            None,
133            Some(12345),
134            Some(89),
135            Some(-3456),
136        ])));
137        let expected = &Int32Array::from(vec![Some(1), None, Some(6), Some(4), Some(54)]);
138
139        let ColumnarValue::Array(result) = spark_bit_count([args])? else {
140            unreachable!()
141        };
142
143        let result = as_int32_array(&result).expect("failed to downcast to In32Array");
144        assert_eq!(result, expected);
145
146        Ok(())
147    }
148}