Skip to main content

polybox_core/
sends.rs

1use super::*;
2use std::future::Future;
3
4/// Implemented for inboxes that can send messages of type `T`.
5pub trait Sends<T: Message> {
6    /// Sends a message of type `T` to the inbox.
7    fn send(&self, msg: T) -> impl Future<Output = Result<Output<T>, SendError<T>>> + Send + '_;
8
9    /// Same as [`Sends::send`], but blocks the current thread until the message is sent.
10    fn send_blocking(&self, msg: T) -> Result<Output<T>, SendError<T>> {
11        futures::executor::block_on(self.send(msg))
12    }
13}
14
15/// Extension trait for [`Sends`].
16pub trait SendsExt<T: Message>: Sends<T> {
17    /// Sends a message of type `T` to the inbox and waits for a reply, if the message type has a reply type.
18    ///
19    /// This is equivalent to calling [`Sends::send`] and then [`MessageReply::receive`].
20    fn request(
21        &self,
22        msg: T,
23    ) -> impl Future<Output = Result<Reply<T>, RequestError<T>>> + Send + '_ {
24        let fut = self.send(msg);
25
26        async { Ok(fut.await?.receive().await?) }
27    }
28
29    /// Same as [`SendsExt::request`], but blocks the current thread until the reply is received.
30    fn request_blocking(&self, msg: T) -> Result<Reply<T>, RequestError<T>> {
31        Ok(self.send_blocking(msg)?.receive_blocking()?)
32    }
33}
34impl<T: Message, S: Sends<T>> SendsExt<T> for S {}