use std::fmt;
use super::mailbox::{MailboxSendError, MailboxSender};
use super::message::{ActorId, Envelope};
#[derive(Clone)]
pub struct ActorRef {
pub(crate) id: ActorId,
pub(crate) sender: MailboxSender,
}
impl ActorRef {
pub fn new(id: ActorId, sender: MailboxSender) -> Self {
Self { id, sender }
}
pub fn id(&self) -> &ActorId {
&self.id
}
pub async fn tell(&self, payload: impl std::any::Any + Send) -> Result<(), MailboxSendError> {
let envelope = Envelope::new(Box::new(payload), None);
self.sender.send(envelope).await
}
pub async fn tell_from(
&self,
payload: impl std::any::Any + Send,
sender: ActorId,
) -> Result<(), MailboxSendError> {
let envelope = Envelope::new(Box::new(payload), Some(sender));
self.sender.send(envelope).await
}
pub async fn send_envelope(&self, envelope: Envelope) -> Result<(), MailboxSendError> {
self.sender.send(envelope).await
}
pub fn try_tell(&self, payload: impl std::any::Any + Send) -> Result<(), MailboxSendError> {
let envelope = Envelope::new(Box::new(payload), None);
self.sender.try_send(envelope)
}
pub fn is_stopped(&self) -> bool {
self.sender.is_closed()
}
}
impl fmt::Debug for ActorRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ActorRef({})", self.id)
}
}
impl fmt::Display for ActorRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ActorRef({})", self.id)
}
}