use crate::misc::PlumtreeAppMessage;
use crate::node::NodeId;
use bytecodec::bytes::{BytesEncoder, RemainingBytesDecoder, Utf8Decoder, Utf8Encoder};
use bytecodec::{Decode, Encode};
#[derive(Debug, Clone)]
pub struct Message<T: MessagePayload>(PlumtreeAppMessage<T>);
impl<T: MessagePayload> Message<T> {
pub fn id(&self) -> &MessageId {
&self.0.id
}
pub fn payload(&self) -> &T {
&self.0.payload
}
pub fn payload_mut(&mut self) -> &mut T {
&mut self.0.payload
}
pub fn into_payload(self) -> T {
self.0.payload
}
pub(crate) fn new(message: PlumtreeAppMessage<T>) -> Self {
Message(message)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MessageId {
node: NodeId,
seqno: u64,
}
impl MessageId {
pub fn node(&self) -> NodeId {
self.node
}
pub fn seqno(&self) -> u64 {
self.seqno
}
pub(crate) fn new(node: NodeId, seqno: u64) -> Self {
MessageId { node, seqno }
}
}
pub trait MessagePayload: Sized + Clone + Send + 'static {
type Encoder: Encode<Item = Self> + Default + Send + 'static;
type Decoder: Decode<Item = Self> + Default + Send + 'static;
}
impl MessagePayload for Vec<u8> {
type Encoder = BytesEncoder<Vec<u8>>;
type Decoder = RemainingBytesDecoder;
}
impl MessagePayload for String {
type Encoder = Utf8Encoder;
type Decoder = Utf8Decoder;
}