use std::{
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use futures::prelude::*;
use libp2p_webrtc_utils::MAX_MSG_LEN;
use tokio_util::compat::{Compat, TokioAsyncReadCompatExt};
use webrtc::data::data_channel::{DataChannel, PollDataChannel};
pub struct Stream {
inner: libp2p_webrtc_utils::Stream<Compat<PollDataChannel>>,
}
pub(crate) type DropListener = libp2p_webrtc_utils::DropListener<Compat<PollDataChannel>>;
impl Stream {
pub(crate) fn new(data_channel: Arc<DataChannel>) -> (Self, DropListener) {
let mut data_channel = PollDataChannel::new(data_channel).compat();
data_channel.get_mut().set_read_buf_capacity(MAX_MSG_LEN);
let (inner, drop_listener) = libp2p_webrtc_utils::Stream::new(data_channel);
(Self { inner }, drop_listener)
}
}
impl AsyncRead for Stream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.get_mut().inner).poll_read(cx, buf)
}
}
impl AsyncWrite for Stream {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_close(cx)
}
}