futures_util/io/
split.rs

1use crate::lock::BiLock;
2use core::fmt;
3use futures_core::ready;
4use futures_core::task::{Context, Poll};
5use futures_io::{AsyncRead, AsyncWrite, IoSlice, IoSliceMut};
6use std::io;
7use std::pin::Pin;
8
9/// The readable half of an object returned from `AsyncRead::split`.
10#[derive(Debug)]
11pub struct ReadHalf<T> {
12    handle: BiLock<T>,
13}
14
15/// The writable half of an object returned from `AsyncRead::split`.
16#[derive(Debug)]
17pub struct WriteHalf<T> {
18    handle: BiLock<T>,
19}
20
21fn lock_and_then<T, U, E, F>(lock: &BiLock<T>, cx: &mut Context<'_>, f: F) -> Poll<Result<U, E>>
22where
23    F: FnOnce(Pin<&mut T>, &mut Context<'_>) -> Poll<Result<U, E>>,
24{
25    let mut l = ready!(lock.poll_lock(cx));
26    f(l.as_pin_mut(), cx)
27}
28
29pub(super) fn split<T: AsyncRead + AsyncWrite>(t: T) -> (ReadHalf<T>, WriteHalf<T>) {
30    let (a, b) = BiLock::new(t);
31    (ReadHalf { handle: a }, WriteHalf { handle: b })
32}
33
34impl<T> ReadHalf<T> {
35    /// Checks if this `ReadHalf` and some `WriteHalf` were split from the same stream.
36    pub fn is_pair_of(&self, other: &WriteHalf<T>) -> bool {
37        self.handle.is_pair_of(&other.handle)
38    }
39}
40
41impl<T: Unpin> ReadHalf<T> {
42    /// Attempts to put the two "halves" of a split `AsyncRead + AsyncWrite` back
43    /// together. Succeeds only if the `ReadHalf<T>` and `WriteHalf<T>` are
44    /// a matching pair originating from the same call to `AsyncReadExt::split`.
45    pub fn reunite(self, other: WriteHalf<T>) -> Result<T, ReuniteError<T>> {
46        self.handle
47            .reunite(other.handle)
48            .map_err(|err| ReuniteError(ReadHalf { handle: err.0 }, WriteHalf { handle: err.1 }))
49    }
50}
51
52impl<T> WriteHalf<T> {
53    /// Checks if this `WriteHalf` and some `ReadHalf` were split from the same stream.
54    pub fn is_pair_of(&self, other: &ReadHalf<T>) -> bool {
55        self.handle.is_pair_of(&other.handle)
56    }
57}
58
59impl<T: Unpin> WriteHalf<T> {
60    /// Attempts to put the two "halves" of a split `AsyncRead + AsyncWrite` back
61    /// together. Succeeds only if the `ReadHalf<T>` and `WriteHalf<T>` are
62    /// a matching pair originating from the same call to `AsyncReadExt::split`.
63    pub fn reunite(self, other: ReadHalf<T>) -> Result<T, ReuniteError<T>> {
64        other.reunite(self)
65    }
66}
67
68impl<R: AsyncRead> AsyncRead for ReadHalf<R> {
69    fn poll_read(
70        self: Pin<&mut Self>,
71        cx: &mut Context<'_>,
72        buf: &mut [u8],
73    ) -> Poll<io::Result<usize>> {
74        lock_and_then(&self.handle, cx, |l, cx| l.poll_read(cx, buf))
75    }
76
77    fn poll_read_vectored(
78        self: Pin<&mut Self>,
79        cx: &mut Context<'_>,
80        bufs: &mut [IoSliceMut<'_>],
81    ) -> Poll<io::Result<usize>> {
82        lock_and_then(&self.handle, cx, |l, cx| l.poll_read_vectored(cx, bufs))
83    }
84}
85
86impl<W: AsyncWrite> AsyncWrite for WriteHalf<W> {
87    fn poll_write(
88        self: Pin<&mut Self>,
89        cx: &mut Context<'_>,
90        buf: &[u8],
91    ) -> Poll<io::Result<usize>> {
92        lock_and_then(&self.handle, cx, |l, cx| l.poll_write(cx, buf))
93    }
94
95    fn poll_write_vectored(
96        self: Pin<&mut Self>,
97        cx: &mut Context<'_>,
98        bufs: &[IoSlice<'_>],
99    ) -> Poll<io::Result<usize>> {
100        lock_and_then(&self.handle, cx, |l, cx| l.poll_write_vectored(cx, bufs))
101    }
102
103    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
104        lock_and_then(&self.handle, cx, |l, cx| l.poll_flush(cx))
105    }
106
107    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
108        lock_and_then(&self.handle, cx, |l, cx| l.poll_close(cx))
109    }
110}
111
112/// Error indicating a `ReadHalf<T>` and `WriteHalf<T>` were not two halves
113/// of a `AsyncRead + AsyncWrite`, and thus could not be `reunite`d.
114pub struct ReuniteError<T>(pub ReadHalf<T>, pub WriteHalf<T>);
115
116impl<T> fmt::Debug for ReuniteError<T> {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.debug_tuple("ReuniteError").field(&"...").finish()
119    }
120}
121
122impl<T> fmt::Display for ReuniteError<T> {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        write!(f, "tried to reunite a ReadHalf and WriteHalf that don't form a pair")
125    }
126}
127
128#[cfg(feature = "std")]
129impl<T: core::any::Any> std::error::Error for ReuniteError<T> {}