2 use delegate::delegate;
3 use mt_ser::{DefCfg, MtDeserialize, MtSerialize};
4 use std::{borrow::Cow, io};
8 type UdpPeer: mt_rudp::UdpPeer;
9 type PktFrom: MtDeserialize;
10 type PktTo: MtSerialize + PktInfo;
13 #[cfg(feature = "client")]
16 #[cfg(feature = "client")]
17 impl Peer for RemoteSrv {
18 type UdpPeer = mt_rudp::RemoteSrv;
19 type PktTo = crate::ToSrvPkt;
20 type PktFrom = crate::ToCltPkt;
23 #[cfg(feature = "client")]
24 pub async fn connect(addr: &str) -> io::Result<(MtSender<RemoteSrv>, MtReceiver<RemoteSrv>)> {
25 let (tx, rx) = mt_rudp::connect(addr).await?;
26 Ok((MtSender(tx), MtReceiver(rx)))
31 #[cfg(feature = "server")]
34 #[cfg(feature = "server")]
35 impl Peer for RemoteClt {
36 type UdpPeer = mt_rudp::RemoteClt;
37 type To = crate::ToCltPkt;
38 type From = crate::ToSrvPkt;
43 pub struct MtSender<P: Peer>(pub mt_rudp::RudpSender<P::UdpPeer>);
44 pub struct MtReceiver<P: Peer>(pub mt_rudp::RudpReceiver<P::UdpPeer>);
46 #[derive(Error, Debug)]
48 #[error("connection error: {0}")]
49 ConnError(#[from] mt_rudp::Error),
50 #[error("deserialize error: {0}")]
51 DeserializeError(#[from] mt_ser::DeserializeError),
54 #[derive(Error, Debug)]
56 #[error("connection error: {0}")]
57 ConnError(#[from] io::Error),
58 #[error("serialize error: {0}")]
59 SerializeError(#[from] mt_ser::SerializeError),
62 macro_rules! impl_delegate {
67 pub async fn peer_id(&self) -> u16;
68 pub async fn is_server(&self) -> bool;
69 pub async fn close(self);
76 impl_delegate!(MtSender);
77 impl_delegate!(MtReceiver);
79 impl<P: Peer> MtReceiver<P> {
80 pub async fn recv(&mut self) -> Option<Result<P::PktFrom, RecvError>> {
81 self.0.recv().await.map(|res| {
82 res.map_err(RecvError::from).and_then(|pkt| {
83 // TODO: warn on trailing data
84 P::PktFrom::mt_deserialize::<DefCfg>(&mut io::Cursor::new(pkt.data))
85 .map_err(RecvError::from)
91 impl<P: Peer> MtSender<P> {
92 pub async fn send(&self, pkt: &P::PktTo) -> Result<(), SendError> {
93 let mut writer = Vec::new();
94 pkt.mt_serialize::<DefCfg>(&mut writer)?;
96 let (chan, unrel) = pkt.pkt_info();
101 data: Cow::Borrowed(&writer),
109 // derive(Clone) adds unwanted trait bound to P
110 impl<P: Peer> Clone for MtSender<P> {
111 fn clone(&self) -> Self {