Skip to main content

datafusion_expr/
udf_eq.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::{AggregateUDFImpl, HigherOrderUDFImpl, ScalarUDFImpl, WindowUDFImpl};
6use std::any::Any;
7use std::fmt::Debug;
8use std::hash::{DefaultHasher, Hash, Hasher};
9use std::ops::Deref;
10use std::sync::Arc;
11
12/// A wrapper around a pointer to UDF that implements `Eq` and `Hash` delegating to
13/// corresponding methods on the UDF trait.
14///
15/// If you want to just compare pointers for equality, use [`super::ptr_eq::PtrEq`].
16#[derive(Clone)]
17#[expect(private_bounds)] // This is so that UdfEq can only be used with allowed pointer types (e.g. Arc), without allowing misuse.
18pub struct UdfEq<Ptr: UdfPointer>(Ptr);
19
20impl<Ptr> PartialEq for UdfEq<Ptr>
21where
22    Ptr: UdfPointer,
23{
24    fn eq(&self, other: &Self) -> bool {
25        self.0.equals(&other.0)
26    }
27}
28impl<Ptr> Eq for UdfEq<Ptr> where Ptr: UdfPointer {}
29impl<Ptr> Hash for UdfEq<Ptr>
30where
31    Ptr: UdfPointer,
32{
33    fn hash<H: Hasher>(&self, state: &mut H) {
34        self.0.hash_value().hash(state);
35    }
36}
37
38impl<Ptr> From<Ptr> for UdfEq<Ptr>
39where
40    Ptr: UdfPointer,
41{
42    fn from(ptr: Ptr) -> Self {
43        UdfEq(ptr)
44    }
45}
46
47impl<Ptr> Debug for UdfEq<Ptr>
48where
49    Ptr: UdfPointer + Debug,
50{
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        self.0.fmt(f)
53    }
54}
55
56impl<Ptr> Deref for UdfEq<Ptr>
57where
58    Ptr: UdfPointer,
59{
60    type Target = Ptr;
61
62    fn deref(&self) -> &Self::Target {
63        &self.0
64    }
65}
66
67trait UdfPointer: Deref {
68    fn equals(&self, other: &Self::Target) -> bool;
69    fn hash_value(&self) -> u64;
70}
71
72impl UdfPointer for Arc<dyn ScalarUDFImpl + '_> {
73    fn equals(&self, other: &(dyn ScalarUDFImpl + '_)) -> bool {
74        self.as_ref().dyn_eq(other as &dyn Any)
75    }
76
77    fn hash_value(&self) -> u64 {
78        let hasher = &mut DefaultHasher::new();
79        self.as_ref().dyn_hash(hasher);
80        hasher.finish()
81    }
82}
83
84impl UdfPointer for Arc<dyn HigherOrderUDFImpl + '_> {
85    fn equals(&self, other: &Self::Target) -> bool {
86        self.as_ref().dyn_eq(other)
87    }
88
89    fn hash_value(&self) -> u64 {
90        let hasher = &mut DefaultHasher::new();
91        self.as_ref().dyn_hash(hasher);
92        hasher.finish()
93    }
94}
95
96impl UdfPointer for Arc<dyn AggregateUDFImpl + '_> {
97    fn equals(&self, other: &(dyn AggregateUDFImpl + '_)) -> bool {
98        self.as_ref().dyn_eq(other)
99    }
100
101    fn hash_value(&self) -> u64 {
102        let hasher = &mut DefaultHasher::new();
103        self.as_ref().dyn_hash(hasher);
104        hasher.finish()
105    }
106}
107
108impl UdfPointer for Arc<dyn WindowUDFImpl + '_> {
109    fn equals(&self, other: &(dyn WindowUDFImpl + '_)) -> bool {
110        self.as_ref().dyn_eq(other as &dyn Any)
111    }
112
113    fn hash_value(&self) -> u64 {
114        let hasher = &mut DefaultHasher::new();
115        self.as_ref().dyn_hash(hasher);
116        hasher.finish()
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use crate::ScalarFunctionArgs;
124    use arrow::datatypes::DataType;
125    use datafusion_expr_common::columnar_value::ColumnarValue;
126    use datafusion_expr_common::signature::{Signature, Volatility};
127    use std::hash::DefaultHasher;
128
129    #[derive(Debug, PartialEq, Eq, Hash)]
130    struct TestScalarUDF {
131        signature: Signature,
132        name: &'static str,
133    }
134    impl ScalarUDFImpl for TestScalarUDF {
135        fn name(&self) -> &str {
136            self.name
137        }
138
139        fn signature(&self) -> &Signature {
140            &self.signature
141        }
142
143        fn return_type(
144            &self,
145            _arg_types: &[DataType],
146        ) -> datafusion_common::Result<DataType> {
147            unimplemented!()
148        }
149
150        fn invoke_with_args(
151            &self,
152            _args: ScalarFunctionArgs,
153        ) -> datafusion_common::Result<ColumnarValue> {
154            unimplemented!()
155        }
156    }
157
158    #[test]
159    pub fn test_eq_eq_wrapper() {
160        let signature = Signature::any(1, Volatility::Immutable);
161
162        let a1: Arc<dyn ScalarUDFImpl> = Arc::new(TestScalarUDF {
163            signature: signature.clone(),
164            name: "a",
165        });
166        let a2: Arc<dyn ScalarUDFImpl> = Arc::new(TestScalarUDF {
167            signature: signature.clone(),
168            name: "a",
169        });
170        let b: Arc<dyn ScalarUDFImpl> = Arc::new(TestScalarUDF {
171            signature: signature.clone(),
172            name: "b",
173        });
174
175        // Reflexivity
176        let wrapper = UdfEq(Arc::clone(&a1));
177        assert_eq!(wrapper, wrapper);
178
179        // Two wrappers around equal pointer
180        assert_eq!(UdfEq(Arc::clone(&a1)), UdfEq(Arc::clone(&a1)));
181        assert_eq!(hash(UdfEq(Arc::clone(&a1))), hash(UdfEq(Arc::clone(&a1))));
182
183        // Two wrappers around different pointers but equal in ScalarUDFImpl::equals sense
184        assert_eq!(UdfEq(Arc::clone(&a1)), UdfEq(Arc::clone(&a2)));
185        assert_eq!(hash(UdfEq(Arc::clone(&a1))), hash(UdfEq(Arc::clone(&a2))));
186
187        // different functions (not equal)
188        assert_ne!(UdfEq(Arc::clone(&a1)), UdfEq(Arc::clone(&b)));
189    }
190
191    fn hash<T: Hash>(value: T) -> u64 {
192        let hasher = &mut DefaultHasher::new();
193        value.hash(hasher);
194        hasher.finish()
195    }
196}