Skip to main content

externally_driven_async_rt/net/
borrowed_read_half.rs

1use crate::{io::AsyncRead, selector::Direction};
2
3use super::{NetError, socket::Socket};
4
5/// Read half of a TCP/Unix stream.
6#[must_use]
7pub struct BorrowedReadHalf<'s, 'sel, const FDS: usize> {
8    socket: &'s Socket<'sel, FDS>,
9}
10
11impl<'s, 'sel, const FDS: usize> BorrowedReadHalf<'s, 'sel, FDS> {
12    pub(super) const fn new(socket: &'s Socket<'sel, FDS>) -> Self {
13        Self { socket }
14    }
15
16    /// Waits until the stream is readable.
17    ///
18    /// The stream may still turn out to be not readable, so [`try_read`](Self::try_read)
19    /// can return [`Errno::AGAIN`](rustix::io::Errno::AGAIN) after it.
20    ///
21    /// # Cancel safety
22    ///
23    /// This method is cancel safe.
24    pub async fn readable(&mut self) {
25        self.socket.ready(Direction::Read).await;
26    }
27
28    /// Reads into a given buffer without waiting, returns the number of read bytes.
29    ///
30    /// Returns `0` if the stream is closed (or if the buffer is empty).
31    ///
32    /// # Errors
33    ///
34    /// Returns [`Errno::AGAIN`](rustix::io::Errno::AGAIN) if the stream is not readable,
35    /// or an error if the syscall fails.
36    pub fn try_read(&self, buf: &mut [u8]) -> rustix::io::Result<usize> {
37        self.socket.try_recv(buf)
38    }
39}
40
41impl<const FDS: usize> AsyncRead for BorrowedReadHalf<'_, '_, FDS> {
42    type Error = NetError;
43
44    fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> impl Future<Output = Result<usize, NetError>> {
45        self.socket.recv(buf)
46    }
47}