datafusion_expr_common/dyn_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 std::any::Any;
6use std::hash::{Hash, Hasher};
7
8/// A dyn-compatible version of [`Eq`] trait.
9/// The implementation constraints for this trait are the same as for [`Eq`]:
10/// the implementation must be reflexive, symmetric, and transitive.
11/// Additionally, if two values can be compared with [`DynEq`] and [`PartialEq`] then
12/// they must be [`DynEq`]-equal if and only if they are [`PartialEq`]-equal.
13/// It is therefore strongly discouraged to implement this trait for types
14/// that implement `PartialEq<Other>` or `Eq<Other>` for any type `Other` other than `Self`.
15///
16/// Note: This trait should not be implemented directly. Implement `Eq` and `Any` and use
17/// the blanket implementation.
18#[expect(private_bounds)]
19pub trait DynEq: private::EqSealed {
20 fn dyn_eq(&self, other: &dyn Any) -> bool;
21}
22
23impl<T: Eq + Any> private::EqSealed for T {}
24impl<T: Eq + Any> DynEq for T {
25 fn dyn_eq(&self, other: &dyn Any) -> bool {
26 other.downcast_ref::<Self>() == Some(self)
27 }
28}
29
30/// A dyn-compatible version of [`Hash`] trait.
31/// If two values are equal according to [`DynEq`], they must produce the same hash value.
32///
33/// Note: This trait should not be implemented directly. Implement `Hash` and `Any` and use
34/// the blanket implementation.
35#[expect(private_bounds)]
36pub trait DynHash: private::HashSealed {
37 fn dyn_hash(&self, _state: &mut dyn Hasher);
38}
39
40impl<T: Hash + Any> private::HashSealed for T {}
41impl<T: Hash + Any> DynHash for T {
42 fn dyn_hash(&self, mut state: &mut dyn Hasher) {
43 self.type_id().hash(&mut state);
44 self.hash(&mut state)
45 }
46}
47
48mod private {
49 pub(super) trait EqSealed {}
50 pub(super) trait HashSealed {}
51}