Skip to main content

acktor/message/
result.rs

1use std::fmt::{self, Debug};
2use std::future;
3
4use super::{Message, MessageResponse};
5use crate::actor::Actor;
6use crate::channel::oneshot;
7
8/// A helper type which wraps the result of a message handler as a message response.
9///
10/// This is useful when the result type of a message does not implement [`MessageResponse`],
11/// and you can not implement [`MessageResponse`] for the type due to the orphan rule. In this
12/// case, you can wrap the result type with this type and use it as the
13/// [`Result`][super::Handler::Result] associate type in the [`Handler`][super::Handler] trait.
14pub struct MessageResult<M>(pub M::Result)
15where
16    M: Message;
17
18impl<M> Debug for MessageResult<M>
19where
20    M: Message,
21{
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        f.write_fmt(format_args!(
24            "MessageResult<{}>",
25            crate::utils::type_name::<M>()
26        ))
27    }
28}
29
30impl<A, M> MessageResponse<A, M> for MessageResult<M>
31where
32    A: Actor,
33    M: Message,
34{
35    fn handle(
36        self,
37        _ctx: &mut A::Context,
38        tx: Option<oneshot::Sender<M::Result>>,
39    ) -> impl Future<Output = ()> + Send {
40        if let Some(tx) = tx {
41            let _ = tx.send(self.0);
42        }
43        future::ready(())
44    }
45}