use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::io;
use std::io::{Error, ErrorKind};
use std::sync::mpsc;
pub type PayloadSender = MsgSender<Payload>;
pub type PayloadReceiver = MsgReceiver<Payload>;
impl PayloadSenderHelperMethods for PayloadSender {
fn send_payload(&self, payload: Payload) -> Result<(), Error> {
self.send(payload)
}
}
impl PayloadReceiverHelperMethods for PayloadReceiver {
fn recv_payload(&self) -> Result<Payload, Error> {
self.recv()
}
fn to_mpsc_receiver(self) -> Receiver<Payload> {
self.rx
}
}
pub struct MsgReceiver<T> {
rx: mpsc::Receiver<T>,
}
impl<T> MsgReceiver<T> {
pub fn recv(&self) -> Result<T, Error> {
use std::error::Error;
self.rx.recv().map_err(|e| io::Error::new(ErrorKind::Other, e.description()))
}
}
#[derive(Clone)]
pub struct MsgSender<T> {
tx: mpsc::Sender<T>,
}
impl<T> MsgSender<T> {
pub fn send(&self, data: T) -> Result<(), Error> {
self.tx.send(data).map_err(|_| Error::new(ErrorKind::Other, "cannot send on closed channel"))
}
}
pub fn payload_channel() -> Result<(PayloadSender, PayloadReceiver), Error> {
let (tx, rx) = mpsc::channel();
Ok((PayloadSender { tx }, PayloadReceiver { rx }))
}
pub fn msg_channel<T>() -> Result<(MsgSender<T>, MsgReceiver<T>), Error> {
let (tx, rx) = mpsc::channel();
Ok((MsgSender { tx }, MsgReceiver { rx }))
}
impl<T> Serialize for MsgReceiver<T> {
fn serialize<S: Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
unreachable!();
}
}
impl<T> Serialize for MsgSender<T> {
fn serialize<S: Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
unreachable!();
}
}
impl<'de, T> Deserialize<'de> for MsgReceiver<T> {
fn deserialize<D>(_: D) -> Result<MsgReceiver<T>, D::Error>
where D: Deserializer<'de> {
unreachable!();
}
}
impl<'de, T> Deserialize<'de> for MsgSender<T> {
fn deserialize<D>(_: D) -> Result<MsgSender<T>, D::Error>
where D: Deserializer<'de> {
unreachable!();
}
}