• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! `UnixStream` owned split support.
2 //!
3 //! A `UnixStream` can be split into an `OwnedReadHalf` and a `OwnedWriteHalf`
4 //! with the `UnixStream::into_split` method.  `OwnedReadHalf` implements
5 //! `AsyncRead` while `OwnedWriteHalf` implements `AsyncWrite`.
6 //!
7 //! Compared to the generic split of `AsyncRead + AsyncWrite`, this specialized
8 //! split has no associated overhead and enforces all invariants at the type
9 //! level.
10 
11 use crate::io::{AsyncRead, AsyncWrite, Interest, ReadBuf, Ready};
12 use crate::net::UnixStream;
13 
14 use crate::net::unix::SocketAddr;
15 use std::error::Error;
16 use std::net::Shutdown;
17 use std::pin::Pin;
18 use std::sync::Arc;
19 use std::task::{Context, Poll};
20 use std::{fmt, io};
21 
22 cfg_io_util! {
23     use bytes::BufMut;
24 }
25 
26 /// Owned read half of a [`UnixStream`], created by [`into_split`].
27 ///
28 /// Reading from an `OwnedReadHalf` is usually done using the convenience methods found
29 /// on the [`AsyncReadExt`] trait.
30 ///
31 /// [`UnixStream`]: crate::net::UnixStream
32 /// [`into_split`]: crate::net::UnixStream::into_split()
33 /// [`AsyncReadExt`]: trait@crate::io::AsyncReadExt
34 #[derive(Debug)]
35 pub struct OwnedReadHalf {
36     inner: Arc<UnixStream>,
37 }
38 
39 /// Owned write half of a [`UnixStream`], created by [`into_split`].
40 ///
41 /// Note that in the [`AsyncWrite`] implementation of this type,
42 /// [`poll_shutdown`] will shut down the stream in the write direction.
43 /// Dropping the write half will also shut down the write half of the stream.
44 ///
45 /// Writing to an `OwnedWriteHalf` is usually done using the convenience methods
46 /// found on the [`AsyncWriteExt`] trait.
47 ///
48 /// [`UnixStream`]: crate::net::UnixStream
49 /// [`into_split`]: crate::net::UnixStream::into_split()
50 /// [`AsyncWrite`]: trait@crate::io::AsyncWrite
51 /// [`poll_shutdown`]: fn@crate::io::AsyncWrite::poll_shutdown
52 /// [`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt
53 #[derive(Debug)]
54 pub struct OwnedWriteHalf {
55     inner: Arc<UnixStream>,
56     shutdown_on_drop: bool,
57 }
58 
split_owned(stream: UnixStream) -> (OwnedReadHalf, OwnedWriteHalf)59 pub(crate) fn split_owned(stream: UnixStream) -> (OwnedReadHalf, OwnedWriteHalf) {
60     let arc = Arc::new(stream);
61     let read = OwnedReadHalf {
62         inner: Arc::clone(&arc),
63     };
64     let write = OwnedWriteHalf {
65         inner: arc,
66         shutdown_on_drop: true,
67     };
68     (read, write)
69 }
70 
reunite( read: OwnedReadHalf, write: OwnedWriteHalf, ) -> Result<UnixStream, ReuniteError>71 pub(crate) fn reunite(
72     read: OwnedReadHalf,
73     write: OwnedWriteHalf,
74 ) -> Result<UnixStream, ReuniteError> {
75     if Arc::ptr_eq(&read.inner, &write.inner) {
76         write.forget();
77         // This unwrap cannot fail as the api does not allow creating more than two Arcs,
78         // and we just dropped the other half.
79         Ok(Arc::try_unwrap(read.inner).expect("UnixStream: try_unwrap failed in reunite"))
80     } else {
81         Err(ReuniteError(read, write))
82     }
83 }
84 
85 /// Error indicating that two halves were not from the same socket, and thus could
86 /// not be reunited.
87 #[derive(Debug)]
88 pub struct ReuniteError(pub OwnedReadHalf, pub OwnedWriteHalf);
89 
90 impl fmt::Display for ReuniteError {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result91     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92         write!(
93             f,
94             "tried to reunite halves that are not from the same socket"
95         )
96     }
97 }
98 
99 impl Error for ReuniteError {}
100 
101 impl OwnedReadHalf {
102     /// Attempts to put the two halves of a `UnixStream` back together and
103     /// recover the original socket. Succeeds only if the two halves
104     /// originated from the same call to [`into_split`].
105     ///
106     /// [`into_split`]: crate::net::UnixStream::into_split()
reunite(self, other: OwnedWriteHalf) -> Result<UnixStream, ReuniteError>107     pub fn reunite(self, other: OwnedWriteHalf) -> Result<UnixStream, ReuniteError> {
108         reunite(self, other)
109     }
110 
111     /// Waits for any of the requested ready states.
112     ///
113     /// This function is usually paired with `try_read()` or `try_write()`. It
114     /// can be used to concurrently read / write to the same socket on a single
115     /// task without splitting the socket.
116     ///
117     /// The function may complete without the socket being ready. This is a
118     /// false-positive and attempting an operation will return with
119     /// `io::ErrorKind::WouldBlock`. The function can also return with an empty
120     /// [`Ready`] set, so you should always check the returned value and possibly
121     /// wait again if the requested states are not set.
122     ///
123     /// # Cancel safety
124     ///
125     /// This method is cancel safe. Once a readiness event occurs, the method
126     /// will continue to return immediately until the readiness event is
127     /// consumed by an attempt to read or write that fails with `WouldBlock` or
128     /// `Poll::Pending`.
ready(&self, interest: Interest) -> io::Result<Ready>129     pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
130         self.inner.ready(interest).await
131     }
132 
133     /// Waits for the socket to become readable.
134     ///
135     /// This function is equivalent to `ready(Interest::READABLE)` and is usually
136     /// paired with `try_read()`.
137     ///
138     /// # Cancel safety
139     ///
140     /// This method is cancel safe. Once a readiness event occurs, the method
141     /// will continue to return immediately until the readiness event is
142     /// consumed by an attempt to read that fails with `WouldBlock` or
143     /// `Poll::Pending`.
readable(&self) -> io::Result<()>144     pub async fn readable(&self) -> io::Result<()> {
145         self.inner.readable().await
146     }
147 
148     /// Tries to read data from the stream into the provided buffer, returning how
149     /// many bytes were read.
150     ///
151     /// Receives any pending data from the socket but does not wait for new data
152     /// to arrive. On success, returns the number of bytes read. Because
153     /// `try_read()` is non-blocking, the buffer does not have to be stored by
154     /// the async task and can exist entirely on the stack.
155     ///
156     /// Usually, [`readable()`] or [`ready()`] is used with this function.
157     ///
158     /// [`readable()`]: Self::readable()
159     /// [`ready()`]: Self::ready()
160     ///
161     /// # Return
162     ///
163     /// If data is successfully read, `Ok(n)` is returned, where `n` is the
164     /// number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:
165     ///
166     /// 1. The stream's read half is closed and will no longer yield data.
167     /// 2. The specified buffer was 0 bytes in length.
168     ///
169     /// If the stream is not ready to read data,
170     /// `Err(io::ErrorKind::WouldBlock)` is returned.
try_read(&self, buf: &mut [u8]) -> io::Result<usize>171     pub fn try_read(&self, buf: &mut [u8]) -> io::Result<usize> {
172         self.inner.try_read(buf)
173     }
174 
175     cfg_io_util! {
176         /// Tries to read data from the stream into the provided buffer, advancing the
177         /// buffer's internal cursor, returning how many bytes were read.
178         ///
179         /// Receives any pending data from the socket but does not wait for new data
180         /// to arrive. On success, returns the number of bytes read. Because
181         /// `try_read_buf()` is non-blocking, the buffer does not have to be stored by
182         /// the async task and can exist entirely on the stack.
183         ///
184         /// Usually, [`readable()`] or [`ready()`] is used with this function.
185         ///
186         /// [`readable()`]: Self::readable()
187         /// [`ready()`]: Self::ready()
188         ///
189         /// # Return
190         ///
191         /// If data is successfully read, `Ok(n)` is returned, where `n` is the
192         /// number of bytes read. `Ok(0)` indicates the stream's read half is closed
193         /// and will no longer yield data. If the stream is not ready to read data
194         /// `Err(io::ErrorKind::WouldBlock)` is returned.
195         pub fn try_read_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
196             self.inner.try_read_buf(buf)
197         }
198     }
199 
200     /// Tries to read data from the stream into the provided buffers, returning
201     /// how many bytes were read.
202     ///
203     /// Data is copied to fill each buffer in order, with the final buffer
204     /// written to possibly being only partially filled. This method behaves
205     /// equivalently to a single call to [`try_read()`] with concatenated
206     /// buffers.
207     ///
208     /// Receives any pending data from the socket but does not wait for new data
209     /// to arrive. On success, returns the number of bytes read. Because
210     /// `try_read_vectored()` is non-blocking, the buffer does not have to be
211     /// stored by the async task and can exist entirely on the stack.
212     ///
213     /// Usually, [`readable()`] or [`ready()`] is used with this function.
214     ///
215     /// [`try_read()`]: Self::try_read()
216     /// [`readable()`]: Self::readable()
217     /// [`ready()`]: Self::ready()
218     ///
219     /// # Return
220     ///
221     /// If data is successfully read, `Ok(n)` is returned, where `n` is the
222     /// number of bytes read. `Ok(0)` indicates the stream's read half is closed
223     /// and will no longer yield data. If the stream is not ready to read data
224     /// `Err(io::ErrorKind::WouldBlock)` is returned.
try_read_vectored(&self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize>225     pub fn try_read_vectored(&self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
226         self.inner.try_read_vectored(bufs)
227     }
228 
229     /// Returns the socket address of the remote half of this connection.
peer_addr(&self) -> io::Result<SocketAddr>230     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
231         self.inner.peer_addr()
232     }
233 
234     /// Returns the socket address of the local half of this connection.
local_addr(&self) -> io::Result<SocketAddr>235     pub fn local_addr(&self) -> io::Result<SocketAddr> {
236         self.inner.local_addr()
237     }
238 }
239 
240 impl AsyncRead for OwnedReadHalf {
poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>>241     fn poll_read(
242         self: Pin<&mut Self>,
243         cx: &mut Context<'_>,
244         buf: &mut ReadBuf<'_>,
245     ) -> Poll<io::Result<()>> {
246         self.inner.poll_read_priv(cx, buf)
247     }
248 }
249 
250 impl OwnedWriteHalf {
251     /// Attempts to put the two halves of a `UnixStream` back together and
252     /// recover the original socket. Succeeds only if the two halves
253     /// originated from the same call to [`into_split`].
254     ///
255     /// [`into_split`]: crate::net::UnixStream::into_split()
reunite(self, other: OwnedReadHalf) -> Result<UnixStream, ReuniteError>256     pub fn reunite(self, other: OwnedReadHalf) -> Result<UnixStream, ReuniteError> {
257         reunite(other, self)
258     }
259 
260     /// Destroys the write half, but don't close the write half of the stream
261     /// until the read half is dropped. If the read half has already been
262     /// dropped, this closes the stream.
forget(mut self)263     pub fn forget(mut self) {
264         self.shutdown_on_drop = false;
265         drop(self);
266     }
267 
268     /// Waits for any of the requested ready states.
269     ///
270     /// This function is usually paired with `try_read()` or `try_write()`. It
271     /// can be used to concurrently read / write to the same socket on a single
272     /// task without splitting the socket.
273     ///
274     /// The function may complete without the socket being ready. This is a
275     /// false-positive and attempting an operation will return with
276     /// `io::ErrorKind::WouldBlock`. The function can also return with an empty
277     /// [`Ready`] set, so you should always check the returned value and possibly
278     /// wait again if the requested states are not set.
279     ///
280     /// # Cancel safety
281     ///
282     /// This method is cancel safe. Once a readiness event occurs, the method
283     /// will continue to return immediately until the readiness event is
284     /// consumed by an attempt to read or write that fails with `WouldBlock` or
285     /// `Poll::Pending`.
ready(&self, interest: Interest) -> io::Result<Ready>286     pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
287         self.inner.ready(interest).await
288     }
289 
290     /// Waits for the socket to become writable.
291     ///
292     /// This function is equivalent to `ready(Interest::WRITABLE)` and is usually
293     /// paired with `try_write()`.
294     ///
295     /// # Cancel safety
296     ///
297     /// This method is cancel safe. Once a readiness event occurs, the method
298     /// will continue to return immediately until the readiness event is
299     /// consumed by an attempt to write that fails with `WouldBlock` or
300     /// `Poll::Pending`.
writable(&self) -> io::Result<()>301     pub async fn writable(&self) -> io::Result<()> {
302         self.inner.writable().await
303     }
304 
305     /// Tries to write a buffer to the stream, returning how many bytes were
306     /// written.
307     ///
308     /// The function will attempt to write the entire contents of `buf`, but
309     /// only part of the buffer may be written.
310     ///
311     /// This function is usually paired with `writable()`.
312     ///
313     /// # Return
314     ///
315     /// If data is successfully written, `Ok(n)` is returned, where `n` is the
316     /// number of bytes written. If the stream is not ready to write data,
317     /// `Err(io::ErrorKind::WouldBlock)` is returned.
try_write(&self, buf: &[u8]) -> io::Result<usize>318     pub fn try_write(&self, buf: &[u8]) -> io::Result<usize> {
319         self.inner.try_write(buf)
320     }
321 
322     /// Tries to write several buffers to the stream, returning how many bytes
323     /// were written.
324     ///
325     /// Data is written from each buffer in order, with the final buffer read
326     /// from possible being only partially consumed. This method behaves
327     /// equivalently to a single call to [`try_write()`] with concatenated
328     /// buffers.
329     ///
330     /// This function is usually paired with `writable()`.
331     ///
332     /// [`try_write()`]: Self::try_write()
333     ///
334     /// # Return
335     ///
336     /// If data is successfully written, `Ok(n)` is returned, where `n` is the
337     /// number of bytes written. If the stream is not ready to write data,
338     /// `Err(io::ErrorKind::WouldBlock)` is returned.
try_write_vectored(&self, buf: &[io::IoSlice<'_>]) -> io::Result<usize>339     pub fn try_write_vectored(&self, buf: &[io::IoSlice<'_>]) -> io::Result<usize> {
340         self.inner.try_write_vectored(buf)
341     }
342 
343     /// Returns the socket address of the remote half of this connection.
peer_addr(&self) -> io::Result<SocketAddr>344     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
345         self.inner.peer_addr()
346     }
347 
348     /// Returns the socket address of the local half of this connection.
local_addr(&self) -> io::Result<SocketAddr>349     pub fn local_addr(&self) -> io::Result<SocketAddr> {
350         self.inner.local_addr()
351     }
352 }
353 
354 impl Drop for OwnedWriteHalf {
drop(&mut self)355     fn drop(&mut self) {
356         if self.shutdown_on_drop {
357             let _ = self.inner.shutdown_std(Shutdown::Write);
358         }
359     }
360 }
361 
362 impl AsyncWrite for OwnedWriteHalf {
poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>>363     fn poll_write(
364         self: Pin<&mut Self>,
365         cx: &mut Context<'_>,
366         buf: &[u8],
367     ) -> Poll<io::Result<usize>> {
368         self.inner.poll_write_priv(cx, buf)
369     }
370 
poll_write_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[io::IoSlice<'_>], ) -> Poll<io::Result<usize>>371     fn poll_write_vectored(
372         self: Pin<&mut Self>,
373         cx: &mut Context<'_>,
374         bufs: &[io::IoSlice<'_>],
375     ) -> Poll<io::Result<usize>> {
376         self.inner.poll_write_vectored_priv(cx, bufs)
377     }
378 
is_write_vectored(&self) -> bool379     fn is_write_vectored(&self) -> bool {
380         self.inner.is_write_vectored()
381     }
382 
383     #[inline]
poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>>384     fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
385         // flush is a no-op
386         Poll::Ready(Ok(()))
387     }
388 
389     // `poll_shutdown` on a write half shutdowns the stream in the "write" direction.
poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>>390     fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
391         let res = self.inner.shutdown_std(Shutdown::Write);
392         if res.is_ok() {
393             Pin::into_inner(self).shutdown_on_drop = false;
394         }
395         res.into()
396     }
397 }
398 
399 impl AsRef<UnixStream> for OwnedReadHalf {
as_ref(&self) -> &UnixStream400     fn as_ref(&self) -> &UnixStream {
401         &self.inner
402     }
403 }
404 
405 impl AsRef<UnixStream> for OwnedWriteHalf {
as_ref(&self) -> &UnixStream406     fn as_ref(&self) -> &UnixStream {
407         &self.inner
408     }
409 }
410