1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use crate::error::TheatreError;
use crate::mailbox::address::MessageSender;
use crate::mailbox::Message;
use std::fmt::{Debug, Formatter};
pub struct Recipient<M>
where
M: Message,
{
tx: Box<dyn MessageSender<M>>,
}
impl<M> Recipient<M>
where
M: Message,
{
pub(crate) fn new(sender: Box<dyn MessageSender<M>>) -> Self {
Self { tx: sender }
}
pub async fn send(&mut self, msg: M) -> Result<<M as Message>::Return, TheatreError> {
self.tx.send(msg).await
}
pub async fn try_send(&mut self, msg: M) -> Result<<M as Message>::Return, TheatreError> {
self.tx.try_send(msg).await
}
pub fn try_send_and_forget(&mut self, msg: M) -> Result<(), TheatreError> {
self.tx.try_send_and_forget(msg)
}
}
impl<M> Clone for Recipient<M>
where
M: Message,
{
fn clone(&self) -> Self {
self.tx.clone_recipient()
}
}
impl<M> Debug for Recipient<M>
where
M: Message + Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Recipient<M>").field("tx", &"...").finish()
}
}
#[cfg(test)]
mod test {
use crate::prelude::*;
struct A;
impl Actor for A {}
struct M;
impl Message for M {
type Return = bool;
}
#[async_trait]
impl Handler<M> for A {
async fn handle(&mut self, _: M, _: &mut Context<Self>) -> <M as Message>::Return {
true
}
}
#[tokio::test]
async fn send_msg() {
let addr = A.spawn().await;
let mut recipient = addr.recipient();
assert!(recipient.send(M).await.unwrap())
}
#[tokio::test]
async fn try_send_msg() {
let addr = A.spawn().await;
let mut recipient = addr.recipient();
assert!(recipient.try_send(M).await.unwrap())
}
#[tokio::test]
async fn try_send_and_forget_msg() {
let (addr, mut handle) = A.start().await;
let mut recipient = addr.recipient();
recipient.try_send_and_forget(M).unwrap();
assert!(handle.heartbeat().await)
}
#[tokio::test]
async fn clone_addr() {
let (addr, mut handle) = A.start().await;
let recipient = addr.recipient();
let mut recipient2 = Recipient::clone(&recipient);
assert!(recipient2.send(M).await.unwrap());
assert!(handle.heartbeat().await)
}
}