Jefffrey commented on code in PR #19627:
URL: https://github.com/apache/datafusion/pull/19627#discussion_r2832965249


##########
datafusion/spark/src/function/hash/murmur3_hash.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// This is a Spark-compatible MurmurHash3 implementation.
+// The algorithm is based on Austin Appleby's original MurmurHash3:
+//   
https://github.com/aappleby/smhasher/blob/0ff96f7835817a27d0487325b6c16033e2992eb5/src/MurmurHash3.cpp
+// Spark's implementation is derived from Guava's Murmur3_32HashFunction:
+//   
https://github.com/google/guava/blob/master/guava/src/com/google/common/hash/Murmur3_32HashFunction.java
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, ArrowNativeTypeOp, DictionaryArray, Int32Array,
+    types::ArrowDictionaryKeyType,
+};
+use arrow::compute::take;
+use arrow::datatypes::{ArrowNativeType, DataType};
+use datafusion_common::{Result, ScalarValue, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+
+use super::utils::create_hashes_internal;
+
+const DEFAULT_SEED: i32 = 42;
+
+/// Spark-compatible murmur3 hash function.
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hash>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkMurmur3Hash {
+    signature: Signature,
+    aliases: Vec<String>,
+}
+
+impl Default for SparkMurmur3Hash {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkMurmur3Hash {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::variadic_any(Volatility::Immutable),
+            aliases: vec!["hash".to_string()],
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkMurmur3Hash {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "murmur3_hash"
+    }
+
+    fn aliases(&self) -> &[String] {
+        &self.aliases
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        Ok(DataType::Int32)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        if args.args.is_empty() {
+            return exec_err!("murmur3_hash requires at least one argument");
+        }
+
+        let num_rows = args.number_rows;
+
+        // Initialize hashes with seed
+        let mut hashes: Vec<u32> = vec![DEFAULT_SEED as u32; num_rows];
+
+        let arrays = ColumnarValue::values_to_arrays(&args.args)?;
+
+        // Hash each column
+        for (i, col) in arrays.iter().enumerate() {
+            hash_column_murmur3(col, &mut hashes, i == 0)?;
+        }
+
+        // Convert to Int32
+        let result: Vec<i32> = hashes.into_iter().map(|h| h as i32).collect();
+        let result_array = Int32Array::from(result);
+
+        if num_rows == 1 {
+            Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(
+                result_array.value(0),
+            ))))
+        } else {
+            Ok(ColumnarValue::Array(Arc::new(result_array)))
+        }
+    }
+}
+
+/// Spark-compatible murmur3 hash algorithm
+#[inline]
+pub fn spark_compatible_murmur3_hash<T: AsRef<[u8]>>(data: T, seed: u32) -> 
u32 {
+    #[inline]
+    fn mix_k1(mut k1: i32) -> i32 {
+        k1 = k1.mul_wrapping(0xcc9e2d51u32 as i32);
+        k1 = k1.rotate_left(15);
+        k1.mul_wrapping(0x1b873593u32 as i32)
+    }
+
+    #[inline]
+    fn mix_h1(mut h1: i32, k1: i32) -> i32 {
+        h1 ^= k1;
+        h1 = h1.rotate_left(13);
+        h1.mul_wrapping(5).add_wrapping(0xe6546b64u32 as i32)
+    }
+
+    #[inline]
+    fn fmix(mut h1: i32, len: i32) -> i32 {
+        h1 ^= len;
+        h1 ^= (h1 as u32 >> 16) as i32;
+        h1 = h1.mul_wrapping(0x85ebca6bu32 as i32);
+        h1 ^= (h1 as u32 >> 13) as i32;
+        h1 = h1.mul_wrapping(0xc2b2ae35u32 as i32);
+        h1 ^= (h1 as u32 >> 16) as i32;
+        h1
+    }
+
+    #[inline]
+    unsafe fn hash_bytes_by_int(data: &[u8], seed: u32) -> i32 {
+        // SAFETY: caller guarantees data length is aligned to 4 bytes
+        unsafe {
+            let mut h1 = seed as i32;
+            for i in (0..data.len()).step_by(4) {
+                let ints = data.as_ptr().add(i) as *const i32;
+                let half_word = ints.read_unaligned();
+                h1 = mix_h1(h1, mix_k1(half_word));
+            }
+            h1
+        }
+    }
+
+    let data = data.as_ref();
+    let len = data.len();
+    let len_aligned = len - len % 4;
+
+    // SAFETY:
+    // Avoid boundary checking in performance critical code.
+    // All operations are guaranteed to be safe.
+    // data is &[u8] so we do not need to check for proper alignment.
+    unsafe {
+        let mut h1 = if len_aligned > 0 {
+            hash_bytes_by_int(&data[0..len_aligned], seed)
+        } else {
+            seed as i32
+        };
+
+        for i in len_aligned..len {
+            let half_word = *data.get_unchecked(i) as i8 as i32;
+            h1 = mix_h1(h1, mix_k1(half_word));
+        }
+        fmix(h1, len as i32) as u32
+    }
+}
+
+/// Hash the values in a dictionary array
+fn hash_column_dictionary<K: ArrowDictionaryKeyType>(
+    array: &ArrayRef,
+    hashes: &mut [u32],
+    first_col: bool,
+) -> Result<()> {
+    let dict_array = 
array.as_any().downcast_ref::<DictionaryArray<K>>().unwrap();
+    if !first_col {
+        let unpacked = take(dict_array.values().as_ref(), dict_array.keys(), 
None)?;
+        hash_column_murmur3(&unpacked, hashes, false)?;
+    } else {

Review Comment:
   Whats the reason for this difference in behaviour for `first_col`?



##########
datafusion/spark/src/function/hash/murmur3_hash.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// This is a Spark-compatible MurmurHash3 implementation.
+// The algorithm is based on Austin Appleby's original MurmurHash3:
+//   
https://github.com/aappleby/smhasher/blob/0ff96f7835817a27d0487325b6c16033e2992eb5/src/MurmurHash3.cpp
+// Spark's implementation is derived from Guava's Murmur3_32HashFunction:
+//   
https://github.com/google/guava/blob/master/guava/src/com/google/common/hash/Murmur3_32HashFunction.java
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, ArrowNativeTypeOp, DictionaryArray, Int32Array,
+    types::ArrowDictionaryKeyType,
+};
+use arrow::compute::take;
+use arrow::datatypes::{ArrowNativeType, DataType};
+use datafusion_common::{Result, ScalarValue, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+
+use super::utils::create_hashes_internal;
+
+const DEFAULT_SEED: i32 = 42;
+
+/// Spark-compatible murmur3 hash function.
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hash>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkMurmur3Hash {
+    signature: Signature,
+    aliases: Vec<String>,
+}
+
+impl Default for SparkMurmur3Hash {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkMurmur3Hash {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::variadic_any(Volatility::Immutable),
+            aliases: vec!["hash".to_string()],
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkMurmur3Hash {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "murmur3_hash"
+    }
+
+    fn aliases(&self) -> &[String] {
+        &self.aliases
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        Ok(DataType::Int32)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        if args.args.is_empty() {
+            return exec_err!("murmur3_hash requires at least one argument");
+        }
+
+        let num_rows = args.number_rows;
+
+        // Initialize hashes with seed
+        let mut hashes: Vec<u32> = vec![DEFAULT_SEED as u32; num_rows];
+
+        let arrays = ColumnarValue::values_to_arrays(&args.args)?;
+
+        // Hash each column
+        for (i, col) in arrays.iter().enumerate() {
+            hash_column_murmur3(col, &mut hashes, i == 0)?;
+        }
+
+        // Convert to Int32
+        let result: Vec<i32> = hashes.into_iter().map(|h| h as i32).collect();
+        let result_array = Int32Array::from(result);
+
+        if num_rows == 1 {
+            Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(
+                result_array.value(0),
+            ))))
+        } else {
+            Ok(ColumnarValue::Array(Arc::new(result_array)))
+        }
+    }
+}
+
+/// Spark-compatible murmur3 hash algorithm
+#[inline]
+pub fn spark_compatible_murmur3_hash<T: AsRef<[u8]>>(data: T, seed: u32) -> 
u32 {
+    #[inline]
+    fn mix_k1(mut k1: i32) -> i32 {
+        k1 = k1.mul_wrapping(0xcc9e2d51u32 as i32);
+        k1 = k1.rotate_left(15);
+        k1.mul_wrapping(0x1b873593u32 as i32)
+    }
+
+    #[inline]
+    fn mix_h1(mut h1: i32, k1: i32) -> i32 {
+        h1 ^= k1;
+        h1 = h1.rotate_left(13);
+        h1.mul_wrapping(5).add_wrapping(0xe6546b64u32 as i32)
+    }
+
+    #[inline]
+    fn fmix(mut h1: i32, len: i32) -> i32 {
+        h1 ^= len;
+        h1 ^= (h1 as u32 >> 16) as i32;
+        h1 = h1.mul_wrapping(0x85ebca6bu32 as i32);
+        h1 ^= (h1 as u32 >> 13) as i32;
+        h1 = h1.mul_wrapping(0xc2b2ae35u32 as i32);
+        h1 ^= (h1 as u32 >> 16) as i32;
+        h1
+    }
+
+    #[inline]
+    unsafe fn hash_bytes_by_int(data: &[u8], seed: u32) -> i32 {
+        // SAFETY: caller guarantees data length is aligned to 4 bytes
+        unsafe {
+            let mut h1 = seed as i32;
+            for i in (0..data.len()).step_by(4) {
+                let ints = data.as_ptr().add(i) as *const i32;
+                let half_word = ints.read_unaligned();
+                h1 = mix_h1(h1, mix_k1(half_word));
+            }
+            h1
+        }
+    }
+
+    let data = data.as_ref();
+    let len = data.len();
+    let len_aligned = len - len % 4;
+
+    // SAFETY:
+    // Avoid boundary checking in performance critical code.
+    // All operations are guaranteed to be safe.
+    // data is &[u8] so we do not need to check for proper alignment.
+    unsafe {
+        let mut h1 = if len_aligned > 0 {
+            hash_bytes_by_int(&data[0..len_aligned], seed)
+        } else {
+            seed as i32
+        };
+
+        for i in len_aligned..len {
+            let half_word = *data.get_unchecked(i) as i8 as i32;
+            h1 = mix_h1(h1, mix_k1(half_word));
+        }
+        fmix(h1, len as i32) as u32
+    }
+}
+
+/// Hash the values in a dictionary array
+fn hash_column_dictionary<K: ArrowDictionaryKeyType>(
+    array: &ArrayRef,
+    hashes: &mut [u32],
+    first_col: bool,
+) -> Result<()> {
+    let dict_array = 
array.as_any().downcast_ref::<DictionaryArray<K>>().unwrap();
+    if !first_col {
+        let unpacked = take(dict_array.values().as_ref(), dict_array.keys(), 
None)?;
+        hash_column_murmur3(&unpacked, hashes, false)?;
+    } else {
+        let dict_values = Arc::clone(dict_array.values());
+        let mut dict_hashes = vec![DEFAULT_SEED as u32; dict_values.len()];
+        hash_column_murmur3(&dict_values, &mut dict_hashes, true)?;
+        for (hash, key) in hashes.iter_mut().zip(dict_array.keys().iter()) {
+            if let Some(key) = key {
+                let idx = key.to_usize().ok_or_else(|| {
+                    datafusion_common::DataFusionError::Internal(format!(
+                        "Can not convert key value {:?} to usize in dictionary 
of type {:?}",
+                        key,
+                        dict_array.data_type()
+                    ))
+                })?;
+                *hash = dict_hashes[idx]
+            }
+            // No update for Null keys, consistent with other types
+        }
+    }
+    Ok(())
+}
+
+/// Create hashes for a batch of arrays (used for recursive hashing of complex 
types).
+fn create_murmur3_hashes(arrays: &[ArrayRef], hashes: &mut [u32]) -> 
Result<()> {
+    for (i, col) in arrays.iter().enumerate() {
+        hash_column_murmur3(col, hashes, i == 0)?;
+    }
+    Ok(())
+}
+
+fn hash_column_murmur3(
+    col: &ArrayRef,
+    hashes: &mut [u32],
+    first_col: bool,
+) -> Result<()> {
+    // Handle Dictionary types separately (turbofish syntax not supported in 
macros)
+    if let DataType::Dictionary(key_type, _) = col.data_type() {

Review Comment:
   Could we use 
[`downcast_dictionary_array`](https://docs.rs/arrow/latest/arrow/macro.downcast_dictionary_array.html)
 here to cut down some boilerplate?



##########
datafusion/spark/src/function/hash/murmur3_hash.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// This is a Spark-compatible MurmurHash3 implementation.
+// The algorithm is based on Austin Appleby's original MurmurHash3:
+//   
https://github.com/aappleby/smhasher/blob/0ff96f7835817a27d0487325b6c16033e2992eb5/src/MurmurHash3.cpp
+// Spark's implementation is derived from Guava's Murmur3_32HashFunction:
+//   
https://github.com/google/guava/blob/master/guava/src/com/google/common/hash/Murmur3_32HashFunction.java
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, ArrowNativeTypeOp, DictionaryArray, Int32Array,
+    types::ArrowDictionaryKeyType,
+};
+use arrow::compute::take;
+use arrow::datatypes::{ArrowNativeType, DataType};
+use datafusion_common::{Result, ScalarValue, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+
+use super::utils::create_hashes_internal;
+
+const DEFAULT_SEED: i32 = 42;
+
+/// Spark-compatible murmur3 hash function.
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hash>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkMurmur3Hash {
+    signature: Signature,
+    aliases: Vec<String>,
+}
+
+impl Default for SparkMurmur3Hash {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkMurmur3Hash {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::variadic_any(Volatility::Immutable),
+            aliases: vec!["hash".to_string()],
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkMurmur3Hash {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "murmur3_hash"
+    }
+
+    fn aliases(&self) -> &[String] {
+        &self.aliases
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        Ok(DataType::Int32)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        if args.args.is_empty() {
+            return exec_err!("murmur3_hash requires at least one argument");
+        }
+
+        let num_rows = args.number_rows;
+
+        // Initialize hashes with seed
+        let mut hashes: Vec<u32> = vec![DEFAULT_SEED as u32; num_rows];
+
+        let arrays = ColumnarValue::values_to_arrays(&args.args)?;
+
+        // Hash each column
+        for (i, col) in arrays.iter().enumerate() {
+            hash_column_murmur3(col, &mut hashes, i == 0)?;
+        }
+
+        // Convert to Int32
+        let result: Vec<i32> = hashes.into_iter().map(|h| h as i32).collect();
+        let result_array = Int32Array::from(result);
+
+        if num_rows == 1 {
+            Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(
+                result_array.value(0),
+            ))))
+        } else {
+            Ok(ColumnarValue::Array(Arc::new(result_array)))
+        }
+    }
+}
+
+/// Spark-compatible murmur3 hash algorithm
+#[inline]
+pub fn spark_compatible_murmur3_hash<T: AsRef<[u8]>>(data: T, seed: u32) -> 
u32 {

Review Comment:
   ```suggestion
   fn spark_compatible_murmur3_hash<T: AsRef<[u8]>>(data: T, seed: u32) -> u32 {
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to