use std::fmt::{self, Debug};
use std::sync::Arc;
use bytes::Bytes;
use super::Message;
use crate::channel::oneshot;
use crate::codec::{DecodeContext, EncodeContext};
pub struct BinaryMessage {
pub actor_id: u64,
pub message_id: u64,
pub bytes: Bytes,
pub result_tx: Option<oneshot::Sender<Bytes>>,
pub decode_msg_ctx: Option<Arc<dyn DecodeContext + Send + Sync>>,
pub encode_res_ctx: Option<Arc<dyn EncodeContext + Send + Sync>>,
}
impl Debug for BinaryMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct(match &self.result_tx {
Some(_) => "BinaryMessage<Send>",
None => "BinaryMessage<DoSend>",
})
.field("actor_id", &self.actor_id)
.field("message_id", &self.message_id)
.field("bytes", &format_args!("Bytes({})", self.bytes.len()))
.finish()
}
}
impl Message for BinaryMessage {
type Result = ();
}
impl BinaryMessage {
pub fn do_send(actor_id: u64, message_id: u64, bytes: Bytes) -> Self {
Self {
actor_id,
message_id,
bytes,
result_tx: None,
decode_msg_ctx: None,
encode_res_ctx: None,
}
}
pub fn send(actor_id: u64, message_id: u64, bytes: Bytes, tx: oneshot::Sender<Bytes>) -> Self {
Self {
actor_id,
message_id,
bytes,
result_tx: Some(tx),
decode_msg_ctx: None,
encode_res_ctx: None,
}
}
pub fn with_decode_context(mut self, context: Arc<dyn DecodeContext + Send + Sync>) -> Self {
self.decode_msg_ctx = Some(context);
self
}
pub fn with_encode_context(mut self, context: Arc<dyn EncodeContext + Send + Sync>) -> Self {
self.encode_res_ctx = Some(context);
self
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn test_debug_fmt() {
let msg = BinaryMessage::do_send(7, 99, Bytes::from_static(b"hello"));
assert_eq!(
format!("{:?}", msg),
"BinaryMessage<DoSend> { actor_id: 7, message_id: 99, bytes: Bytes(5) }"
);
let (tx, _rx) = oneshot::channel::<Bytes>();
let msg = BinaryMessage::send(7, 99, Bytes::from_static(b"hi"), tx);
assert_eq!(
format!("{:?}", msg),
"BinaryMessage<Send> { actor_id: 7, message_id: 99, bytes: Bytes(2) }"
);
}
}