use std::cell::RefCell;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use std::{fmt, io};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
pub struct ReadHalf<T: AsyncRead>(Rc<RefCell<T>>);
pub struct WriteHalf<T: AsyncWrite>(Rc<RefCell<T>>);
pub fn split<T: AsyncRead + AsyncWrite>(value: T) -> (ReadHalf<T>, WriteHalf<T>) {
let shared = Rc::new(RefCell::new(value));
(ReadHalf(shared.clone()), WriteHalf(shared))
}
fn with_pin<T, R>(half: &RefCell<T>, f: impl FnOnce(Pin<&mut T>) -> R) -> R {
let mut guard = half.borrow_mut();
let stream = unsafe { Pin::new_unchecked(&mut *guard) };
f(stream)
}
impl<T: AsyncRead> AsyncRead for ReadHalf<T> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
with_pin(&self.0, |inner| inner.poll_read(cx, buf))
}
}
impl<T: AsyncWrite> AsyncWrite for WriteHalf<T> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
with_pin(&self.0, |inner| inner.poll_write(cx, buf))
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
with_pin(&self.0, |inner| inner.poll_flush(cx))
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
with_pin(&self.0, |inner| inner.poll_shutdown(cx))
}
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[io::IoSlice<'_>],
) -> Poll<Result<usize, io::Error>> {
with_pin(&self.0, |inner| inner.poll_write_vectored(cx, bufs))
}
fn is_write_vectored(&self) -> bool {
self.0.borrow().is_write_vectored()
}
}
impl<T: fmt::Debug + AsyncRead> fmt::Debug for ReadHalf<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("ReadHalf").field(&self.0.borrow()).finish()
}
}
impl<T: fmt::Debug + AsyncWrite> fmt::Debug for WriteHalf<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("WriteHalf").field(&self.0.borrow()).finish()
}
}