roopes_core/primitives/handler/
hash.rs

1//! Provides a [`Hash`] and [`Eq`]-implementing
2//! [`Handler`] which redirects
3//! [`Handler::handle`] calls to a delegate
4//! [`Handler`].  Useful to allow for handlers to
5//! be compared.
6
7use super::Handler;
8use std::{
9    hash::Hash,
10    marker::PhantomData,
11};
12
13/// Stores an indirected [`Handler`] in a [`Box`]
14/// for later delegation, along with an `id` for
15/// delegation with [`Eq`] and [`Hash`].
16#[derive(Clone)]
17pub struct Hashable<D, M, H>
18where
19    D: Handler<M>,
20    H: Hash + Eq,
21{
22    delegate: D,
23    id: H,
24    _t: PhantomData<M>,
25}
26
27impl<D, M, H> Hashable<D, M, H>
28where
29    D: Handler<M>,
30    H: Hash + Eq,
31{
32    /// Creates a new [`Hashable`] from a given
33    /// delegate [`Handler`] and an `id`
34    /// to enable the new [`Hashable`] to delegate
35    /// [`Hash`] and [`Eq`].
36    pub fn new(
37        delegate: D,
38        id: H,
39    ) -> Hashable<D, M, H>
40    {
41        Hashable {
42            delegate,
43            id,
44            _t: PhantomData,
45        }
46    }
47}
48
49impl<D, M, H> Handler<M> for Hashable<D, M, H>
50where
51    D: Handler<M>,
52    H: Hash + Eq,
53{
54    fn handle(
55        &self,
56        message: &M,
57    )
58    {
59        self.delegate.handle(message);
60    }
61}
62
63impl<D, M, H> PartialEq for Hashable<D, M, H>
64where
65    D: Handler<M>,
66    H: Hash + Eq,
67{
68    fn eq(
69        &self,
70        other: &Self,
71    ) -> bool
72    {
73        self.id.eq(&other.id)
74    }
75}
76
77impl<D, M, H> Eq for Hashable<D, M, H>
78where
79    D: Handler<M>,
80    H: Hash + Eq,
81{
82}
83
84impl<D, M, H> Hash for Hashable<D, M, H>
85where
86    D: Handler<M>,
87    H: Hash + Eq,
88{
89    fn hash<S: std::hash::Hasher>(
90        &self,
91        state: &mut S,
92    )
93    {
94        self.id.hash(state);
95    }
96}