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


##########
datafusion/spark/src/function/hash/xxhash64.rs:
##########
@@ -0,0 +1,391 @@
+// 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.
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, AsArray, BinaryArray, BooleanArray, Date32Array, 
Date64Array,
+    Decimal128Array, Float32Array, Float64Array, Int8Array, Int16Array, 
Int32Array,
+    Int64Array, LargeBinaryArray, LargeStringArray, StringArray,
+    TimestampMicrosecondArray, TimestampMillisecondArray, 
TimestampNanosecondArray,
+    TimestampSecondArray,
+};
+use arrow::datatypes::{DataType, TimeUnit};
+use datafusion_common::{Result, ScalarValue, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use twox_hash::XxHash64;
+
+const DEFAULT_SEED: i64 = 42;
+
+/// Spark-compatible xxhash64 function.
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#xxhash64>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkXxhash64 {
+    signature: Signature,
+}
+
+impl Default for SparkXxhash64 {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkXxhash64 {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::variadic_any(Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkXxhash64 {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "xxhash64"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        Ok(DataType::Int64)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        if args.args.is_empty() {
+            return exec_err!("xxhash64 requires at least one argument");
+        }
+
+        // Determine number of rows from the first array argument
+        let num_rows = args
+            .args
+            .iter()
+            .find_map(|arg| match arg {
+                ColumnarValue::Array(array) => Some(array.len()),
+                ColumnarValue::Scalar(_) => None,
+            })
+            .unwrap_or(1);

Review Comment:
   ```suggestion
           let num_rows = args.number_rows;
   ```



##########
datafusion/spark/src/function/hash/murmur3_hash.rs:
##########
@@ -0,0 +1,474 @@
+// 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.
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, ArrowNativeTypeOp, AsArray, BinaryArray, BooleanArray, 
Date32Array,
+    Date64Array, Decimal128Array, Float32Array, Float64Array, Int8Array, 
Int16Array,
+    Int32Array, Int64Array, LargeBinaryArray, LargeStringArray, StringArray,
+    TimestampMicrosecondArray, TimestampMillisecondArray, 
TimestampNanosecondArray,
+    TimestampSecondArray,
+};
+use arrow::datatypes::{DataType, TimeUnit};
+use datafusion_common::{Result, ScalarValue, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+
+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");
+        }
+
+        // Determine number of rows from the first array argument
+        let num_rows = args
+            .args
+            .iter()
+            .find_map(|arg| match arg {
+                ColumnarValue::Array(array) => Some(array.len()),
+                ColumnarValue::Scalar(_) => None,
+            })
+            .unwrap_or(1);
+
+        // Initialize hashes with seed
+        let mut hashes: Vec<u32> = vec![DEFAULT_SEED as u32; num_rows];
+
+        // Convert all arguments to arrays
+        let arrays: Vec<ArrayRef> = args
+            .args
+            .iter()
+            .map(|arg| match arg {
+                ColumnarValue::Array(array) => Arc::clone(array),
+                ColumnarValue::Scalar(scalar) => scalar
+                    .to_array_of_size(num_rows)
+                    .expect("Failed to convert scalar to array"),
+            })
+            .collect();
+
+        // Hash each column
+        for col in &arrays {
+            hash_column_murmur3(col, &mut hashes)?;
+        }
+
+        // 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)
+    }
+

Review Comment:
   Do we need to provide a link to where this source code was extracted from? 
I'm assuming it was ported from some other implementation?



##########
datafusion/spark/src/function/hash/xxhash64.rs:
##########
@@ -0,0 +1,391 @@
+// 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.
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, AsArray, BinaryArray, BooleanArray, Date32Array, 
Date64Array,
+    Decimal128Array, Float32Array, Float64Array, Int8Array, Int16Array, 
Int32Array,
+    Int64Array, LargeBinaryArray, LargeStringArray, StringArray,
+    TimestampMicrosecondArray, TimestampMillisecondArray, 
TimestampNanosecondArray,
+    TimestampSecondArray,
+};
+use arrow::datatypes::{DataType, TimeUnit};
+use datafusion_common::{Result, ScalarValue, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use twox_hash::XxHash64;
+
+const DEFAULT_SEED: i64 = 42;
+
+/// Spark-compatible xxhash64 function.
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#xxhash64>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkXxhash64 {
+    signature: Signature,
+}
+
+impl Default for SparkXxhash64 {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkXxhash64 {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::variadic_any(Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkXxhash64 {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "xxhash64"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        Ok(DataType::Int64)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        if args.args.is_empty() {
+            return exec_err!("xxhash64 requires at least one argument");
+        }
+
+        // Determine number of rows from the first array argument
+        let num_rows = args
+            .args
+            .iter()
+            .find_map(|arg| match arg {
+                ColumnarValue::Array(array) => Some(array.len()),
+                ColumnarValue::Scalar(_) => None,
+            })
+            .unwrap_or(1);
+
+        // Initialize hashes with seed
+        let mut hashes: Vec<u64> = vec![DEFAULT_SEED as u64; num_rows];
+
+        // Convert all arguments to arrays
+        let arrays: Vec<ArrayRef> = args
+            .args
+            .iter()
+            .map(|arg| match arg {
+                ColumnarValue::Array(array) => Arc::clone(array),
+                ColumnarValue::Scalar(scalar) => scalar
+                    .to_array_of_size(num_rows)
+                    .expect("Failed to convert scalar to array"),
+            })
+            .collect();

Review Comment:
   ```suggestion
           let arrays = ColumnarValue::values_to_arrays(&args.args)?;
   ```



##########
datafusion/spark/src/function/hash/murmur3_hash.rs:
##########
@@ -0,0 +1,474 @@
+// 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.
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, ArrowNativeTypeOp, AsArray, BinaryArray, BooleanArray, 
Date32Array,
+    Date64Array, Decimal128Array, Float32Array, Float64Array, Int8Array, 
Int16Array,
+    Int32Array, Int64Array, LargeBinaryArray, LargeStringArray, StringArray,
+    TimestampMicrosecondArray, TimestampMillisecondArray, 
TimestampNanosecondArray,
+    TimestampSecondArray,
+};
+use arrow::datatypes::{DataType, TimeUnit};
+use datafusion_common::{Result, ScalarValue, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+
+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");
+        }
+
+        // Determine number of rows from the first array argument
+        let num_rows = args
+            .args
+            .iter()
+            .find_map(|arg| match arg {
+                ColumnarValue::Array(array) => Some(array.len()),
+                ColumnarValue::Scalar(_) => None,
+            })
+            .unwrap_or(1);
+
+        // Initialize hashes with seed
+        let mut hashes: Vec<u32> = vec![DEFAULT_SEED as u32; num_rows];
+
+        // Convert all arguments to arrays
+        let arrays: Vec<ArrayRef> = args
+            .args
+            .iter()
+            .map(|arg| match arg {
+                ColumnarValue::Array(array) => Arc::clone(array),
+                ColumnarValue::Scalar(scalar) => scalar
+                    .to_array_of_size(num_rows)
+                    .expect("Failed to convert scalar to array"),
+            })
+            .collect();
+
+        // Hash each column
+        for col in &arrays {
+            hash_column_murmur3(col, &mut hashes)?;
+        }
+
+        // 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 mut half_word = ints.read_unaligned();
+                if cfg!(target_endian = "big") {
+                    half_word = half_word.reverse_bits();
+                }
+                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: all operations are guaranteed to be safe
+    unsafe {

Review Comment:
   I'm a bit curious about these unsafe blocks; a safety comment like `all 
operations are guaranteed to be safe` isn't exactly reassuring 😅 



##########
datafusion/spark/src/function/hash/xxhash64.rs:
##########
@@ -0,0 +1,391 @@
+// 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.
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, AsArray, BinaryArray, BooleanArray, Date32Array, 
Date64Array,
+    Decimal128Array, Float32Array, Float64Array, Int8Array, Int16Array, 
Int32Array,
+    Int64Array, LargeBinaryArray, LargeStringArray, StringArray,
+    TimestampMicrosecondArray, TimestampMillisecondArray, 
TimestampNanosecondArray,
+    TimestampSecondArray,
+};
+use arrow::datatypes::{DataType, TimeUnit};
+use datafusion_common::{Result, ScalarValue, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use twox_hash::XxHash64;
+
+const DEFAULT_SEED: i64 = 42;
+
+/// Spark-compatible xxhash64 function.
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#xxhash64>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkXxhash64 {
+    signature: Signature,
+}
+
+impl Default for SparkXxhash64 {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkXxhash64 {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::variadic_any(Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkXxhash64 {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "xxhash64"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        Ok(DataType::Int64)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        if args.args.is_empty() {
+            return exec_err!("xxhash64 requires at least one argument");
+        }
+
+        // Determine number of rows from the first array argument
+        let num_rows = args
+            .args
+            .iter()
+            .find_map(|arg| match arg {
+                ColumnarValue::Array(array) => Some(array.len()),
+                ColumnarValue::Scalar(_) => None,
+            })
+            .unwrap_or(1);
+
+        // Initialize hashes with seed
+        let mut hashes: Vec<u64> = vec![DEFAULT_SEED as u64; num_rows];
+
+        // Convert all arguments to arrays
+        let arrays: Vec<ArrayRef> = args
+            .args
+            .iter()
+            .map(|arg| match arg {
+                ColumnarValue::Array(array) => Arc::clone(array),
+                ColumnarValue::Scalar(scalar) => scalar
+                    .to_array_of_size(num_rows)
+                    .expect("Failed to convert scalar to array"),
+            })
+            .collect();
+
+        // Hash each column
+        for col in &arrays {
+            hash_column_xxhash64(col, &mut hashes)?;
+        }
+
+        // Convert to Int64
+        let result: Vec<i64> = hashes.into_iter().map(|h| h as i64).collect();
+        let result_array = Int64Array::from(result);
+
+        if num_rows == 1 {
+            Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(
+                result_array.value(0),
+            ))))
+        } else {
+            Ok(ColumnarValue::Array(Arc::new(result_array)))
+        }
+    }
+}
+
+#[inline]
+fn spark_compatible_xxhash64<T: AsRef<[u8]>>(data: T, seed: u64) -> u64 {
+    XxHash64::oneshot(seed, data.as_ref())
+}

Review Comment:
   ```suggestion
   #[inline]
   fn spark_compatible_xxhash64<T: AsRef<[u8]>>(data: T, seed: i64) -> i64 {
       XxHash64::oneshot(seed as u64, data.as_ref()) as i64
   }
   ```
   
   I wonder if it's worth doing this to make it easier to compute the resulting 
i64 array, without needing to convert the u64 hash vec to an i64 vec (unless 
compiler optimizes this away anyway 🤔 )



##########
datafusion/spark/src/function/hash/murmur3_hash.rs:
##########
@@ -0,0 +1,474 @@
+// 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.
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, ArrowNativeTypeOp, AsArray, BinaryArray, BooleanArray, 
Date32Array,
+    Date64Array, Decimal128Array, Float32Array, Float64Array, Int8Array, 
Int16Array,
+    Int32Array, Int64Array, LargeBinaryArray, LargeStringArray, StringArray,
+    TimestampMicrosecondArray, TimestampMillisecondArray, 
TimestampNanosecondArray,
+    TimestampSecondArray,
+};
+use arrow::datatypes::{DataType, TimeUnit};
+use datafusion_common::{Result, ScalarValue, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+
+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");
+        }
+
+        // Determine number of rows from the first array argument
+        let num_rows = args
+            .args
+            .iter()
+            .find_map(|arg| match arg {
+                ColumnarValue::Array(array) => Some(array.len()),
+                ColumnarValue::Scalar(_) => None,
+            })
+            .unwrap_or(1);
+
+        // Initialize hashes with seed
+        let mut hashes: Vec<u32> = vec![DEFAULT_SEED as u32; num_rows];
+
+        // Convert all arguments to arrays
+        let arrays: Vec<ArrayRef> = args
+            .args
+            .iter()
+            .map(|arg| match arg {
+                ColumnarValue::Array(array) => Arc::clone(array),
+                ColumnarValue::Scalar(scalar) => scalar
+                    .to_array_of_size(num_rows)
+                    .expect("Failed to convert scalar to array"),
+            })
+            .collect();
+
+        // Hash each column
+        for col in &arrays {
+            hash_column_murmur3(col, &mut hashes)?;
+        }
+
+        // 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 mut half_word = ints.read_unaligned();
+                if cfg!(target_endian = "big") {

Review Comment:
   I remember a previous PR for this same functionality, I'll copy a previous 
comment: https://github.com/apache/datafusion/pull/17093#discussion_r2347906940
   
   > I don't think big endian should be considered; here's a comment from 
arrow-rs about how that doesn't target big endian: 
https://github.com/apache/arrow-rs/issues/6917#issuecomment-2564302613
   >
   > So for simplicity we could just remove this cfg?



-- 
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