use async_lock::Mutex;
use std::io::{Error as IoError, ErrorKind};
use tokio::sync::mpsc::{channel, Receiver, Sender};
pub struct ChannelAdapter {
sender: Sender<Vec<u8>>,
recver: Mutex<Receiver<Vec<u8>>>,
}
impl ChannelAdapter {
pub fn new() -> (Self, Self) {
let (s1, r1) = channel::<Vec<u8>>(32);
let (s2, r2) = channel::<Vec<u8>>(32);
(
Self {
sender: s1.into(),
recver: r2.into(),
},
Self {
sender: s2.into(),
recver: r1.into(),
},
)
}
}
unsafe impl Send for ChannelAdapter {}
unsafe impl Sync for ChannelAdapter {}
#[async_trait::async_trait]
impl crate::Adapter for ChannelAdapter {
async fn send(&self, data: Vec<u8>) -> anyhow::Result<()> {
Ok(self.sender.send(data).await?)
}
async fn recv(&self) -> anyhow::Result<Vec<u8>> {
Ok(self
.recver
.lock()
.await
.recv()
.await
.ok_or(IoError::from(ErrorKind::NotConnected))?)
}
}