1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use crate::{IntoSplit, TypedAsyncRead, TypedAsyncWrite, TypedTransport};
use async_trait::async_trait;
use std::io;
use tokio::sync::mpsc;
mod read;
pub use read::*;
mod write;
pub use write::*;
#[derive(Debug)]
pub struct MpscTransport<T, U> {
outbound: MpscTransportWriteHalf<T>,
inbound: MpscTransportReadHalf<U>,
}
impl<T, U> MpscTransport<T, U> {
pub fn new(outbound: mpsc::Sender<T>, inbound: mpsc::Receiver<U>) -> Self {
Self {
outbound: MpscTransportWriteHalf::new(outbound),
inbound: MpscTransportReadHalf::new(inbound),
}
}
pub fn pair(buffer: usize) -> (MpscTransport<T, U>, MpscTransport<U, T>) {
let (t_tx, t_rx) = mpsc::channel(buffer);
let (u_tx, u_rx) = mpsc::channel(buffer);
(
MpscTransport::new(t_tx, u_rx),
MpscTransport::new(u_tx, t_rx),
)
}
}
impl<T: Send, U: Send> TypedTransport<T, U> for MpscTransport<T, U> {}
#[async_trait]
impl<T: Send, U: Send> TypedAsyncWrite<T> for MpscTransport<T, U> {
async fn write(&mut self, data: T) -> io::Result<()> {
self.outbound
.write(data)
.await
.map_err(|x| io::Error::new(io::ErrorKind::Other, x))
}
}
#[async_trait]
impl<T: Send, U: Send> TypedAsyncRead<U> for MpscTransport<T, U> {
async fn read(&mut self) -> io::Result<Option<U>> {
self.inbound.read().await
}
}
impl<T, U> IntoSplit for MpscTransport<T, U> {
type Read = MpscTransportReadHalf<U>;
type Write = MpscTransportWriteHalf<T>;
fn into_split(self) -> (Self::Write, Self::Read) {
(self.outbound, self.inbound)
}
}