Skip to main content

waft_foundation/
any_eq.rs

1//! Dart's `Object` where it is only compared with `==` and hashed.
2
3use std::any::{Any, TypeId};
4use std::fmt::Debug;
5use std::hash::{Hash, Hasher};
6
7/// Dart's `Object` where it is only compared with `==` and hashed, as a hero's tag or a radio
8/// panel's value: any value, equal only to an equal value of the same type, as two Dart objects
9/// of different classes never are.
10///
11/// The blanket implementation covers every value that can answer both questions, so such a
12/// value is written as `Rc::new("photo")` or `Rc::new(42)`.
13pub trait AnyEq: Any + Debug {
14    /// Dart's `operator ==`. Must return false when `other` is a different concrete type, even
15    /// if the two carry the same value.
16    fn eq_any(&self, other: &dyn AnyEq) -> bool;
17
18    /// Dart's `hashCode`. Must mix in the concrete type so that two types carrying the same
19    /// value do not collide.
20    fn hash_any(&self, state: &mut dyn Hasher);
21}
22
23impl<T: PartialEq + Hash + Debug + 'static> AnyEq for T {
24    fn eq_any(&self, other: &dyn AnyEq) -> bool {
25        (other as &dyn Any)
26            .downcast_ref::<T>()
27            .is_some_and(|other| other == self)
28    }
29
30    fn hash_any(&self, mut state: &mut dyn Hasher) {
31        TypeId::of::<T>().hash(&mut state);
32        self.hash(&mut state);
33    }
34}
35
36impl PartialEq for dyn AnyEq {
37    fn eq(&self, other: &dyn AnyEq) -> bool {
38        self.eq_any(other)
39    }
40}
41
42impl Eq for dyn AnyEq {}
43
44impl Hash for dyn AnyEq {
45    fn hash<H: Hasher>(&self, state: &mut H) {
46        self.hash_any(state);
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use std::collections::hash_map::DefaultHasher;
53    use std::hash::{Hash, Hasher};
54
55    use super::AnyEq;
56
57    fn hash(value: &dyn AnyEq) -> u64 {
58        let mut hasher = DefaultHasher::new();
59        value.hash(&mut hasher);
60        hasher.finish()
61    }
62
63    #[test]
64    fn equal_values_of_one_type_are_equal() {
65        let a: &dyn AnyEq = &"photo";
66        let b: &dyn AnyEq = &"photo";
67        let c: &dyn AnyEq = &"other";
68
69        assert_eq!(a, b);
70        assert_ne!(a, c);
71    }
72
73    #[test]
74    fn equal_looking_values_of_two_types_are_not_equal() {
75        let one: &dyn AnyEq = &1_i32;
76        let another_one: &dyn AnyEq = &1_u32;
77        let one_string: &dyn AnyEq = &"1";
78
79        assert_ne!(one, another_one);
80        assert_ne!(one, one_string);
81    }
82
83    #[test]
84    fn hashing_agrees_with_equality() {
85        assert_eq!(hash(&"photo"), hash(&"photo"));
86        assert_ne!(hash(&1_i32), hash(&1_u32));
87        assert_ne!(hash(&1_i32), hash(&"1"));
88    }
89}