broker_tokio/net/unix/
split.rs

1//! `UnixStream` split support.
2//!
3//! A `UnixStream` can be split into a read half and a write half with
4//! `UnixStream::split`. The read half implements `AsyncRead` while the write
5//! half 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
11use crate::io::{AsyncRead, AsyncWrite};
12use crate::net::UnixStream;
13
14use std::io;
15use std::mem::MaybeUninit;
16use std::net::Shutdown;
17use std::pin::Pin;
18use std::task::{Context, Poll};
19
20/// Read half of a `UnixStream`.
21#[derive(Debug)]
22pub struct ReadHalf<'a>(&'a UnixStream);
23
24/// Write half of a `UnixStream`.
25#[derive(Debug)]
26pub struct WriteHalf<'a>(&'a UnixStream);
27
28pub(crate) fn split(stream: &mut UnixStream) -> (ReadHalf<'_>, WriteHalf<'_>) {
29    (ReadHalf(stream), WriteHalf(stream))
30}
31
32impl AsyncRead for ReadHalf<'_> {
33    unsafe fn prepare_uninitialized_buffer(&self, _: &mut [MaybeUninit<u8>]) -> bool {
34        false
35    }
36
37    fn poll_read(
38        self: Pin<&mut Self>,
39        cx: &mut Context<'_>,
40        buf: &mut [u8],
41    ) -> Poll<io::Result<usize>> {
42        self.0.poll_read_priv(cx, buf)
43    }
44}
45
46impl AsyncWrite for WriteHalf<'_> {
47    fn poll_write(
48        self: Pin<&mut Self>,
49        cx: &mut Context<'_>,
50        buf: &[u8],
51    ) -> Poll<io::Result<usize>> {
52        self.0.poll_write_priv(cx, buf)
53    }
54
55    fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
56        Poll::Ready(Ok(()))
57    }
58
59    fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
60        self.0.shutdown(Shutdown::Write).into()
61    }
62}
63
64impl AsRef<UnixStream> for ReadHalf<'_> {
65    fn as_ref(&self) -> &UnixStream {
66        self.0
67    }
68}
69
70impl AsRef<UnixStream> for WriteHalf<'_> {
71    fn as_ref(&self) -> &UnixStream {
72        self.0
73    }
74}