|
| 1 | +use std::cell::RefCell; |
| 2 | +use std::io; |
| 3 | +use std::pin::Pin; |
| 4 | +use std::rc::Rc; |
| 5 | +use std::task::{Context, Poll}; |
| 6 | +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; |
| 7 | + |
| 8 | +/// The readable half of a value returned from [`split`]. |
| 9 | +pub struct ReadHalf<T: AsyncRead>(Rc<RefCell<T>>); |
| 10 | + |
| 11 | +/// The writable half of a value returned from [`split`]. |
| 12 | +pub struct WriteHalf<T: AsyncWrite>(Rc<RefCell<T>>); |
| 13 | + |
| 14 | +/// Splits a single value implementing `AsyncRead + AsyncWrite` into separate `AsyncRead` and `AsyncWrite` handles. |
| 15 | +/// Non-thread-safe equivalent of [`tokio::io::split`](https://docs.rs/tokio/latest/tokio/io/fn.split.html) without the overhead of a mutex. |
| 16 | +pub fn split<T: AsyncRead + AsyncWrite>(value: T) -> (ReadHalf<T>, WriteHalf<T>) { |
| 17 | + let shared = Rc::new(RefCell::new(value)); |
| 18 | + (ReadHalf(shared.clone()), WriteHalf(shared)) |
| 19 | +} |
| 20 | + |
| 21 | +fn with_pin<T, R>(half: &RefCell<T>, f: impl FnOnce(Pin<&mut T>) -> R) -> R { |
| 22 | + let mut guard = half.borrow_mut(); |
| 23 | + |
| 24 | + // SAFETY: we do not move the stream |
| 25 | + let stream = unsafe { Pin::new_unchecked(&mut *guard) }; |
| 26 | + |
| 27 | + f(stream) |
| 28 | +} |
| 29 | + |
| 30 | +impl<T: AsyncRead> AsyncRead for ReadHalf<T> { |
| 31 | + fn poll_read( |
| 32 | + self: Pin<&mut Self>, |
| 33 | + cx: &mut Context<'_>, |
| 34 | + buf: &mut ReadBuf<'_>, |
| 35 | + ) -> Poll<io::Result<()>> { |
| 36 | + with_pin(&self.0, |inner| inner.poll_read(cx, buf)) |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +impl<T: AsyncWrite> AsyncWrite for WriteHalf<T> { |
| 41 | + fn poll_write( |
| 42 | + self: Pin<&mut Self>, |
| 43 | + cx: &mut Context<'_>, |
| 44 | + buf: &[u8], |
| 45 | + ) -> Poll<Result<usize, io::Error>> { |
| 46 | + with_pin(&self.0, |inner| inner.poll_write(cx, buf)) |
| 47 | + } |
| 48 | + |
| 49 | + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { |
| 50 | + with_pin(&self.0, |inner| inner.poll_flush(cx)) |
| 51 | + } |
| 52 | + |
| 53 | + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { |
| 54 | + with_pin(&self.0, |inner| inner.poll_shutdown(cx)) |
| 55 | + } |
| 56 | + |
| 57 | + fn poll_write_vectored( |
| 58 | + self: Pin<&mut Self>, |
| 59 | + cx: &mut Context<'_>, |
| 60 | + bufs: &[io::IoSlice<'_>], |
| 61 | + ) -> Poll<Result<usize, io::Error>> { |
| 62 | + with_pin(&self.0, |inner| inner.poll_write_vectored(cx, bufs)) |
| 63 | + } |
| 64 | + |
| 65 | + fn is_write_vectored(&self) -> bool { |
| 66 | + self.0.borrow().is_write_vectored() |
| 67 | + } |
| 68 | +} |
0 commit comments