Skip to main content

externally_driven_async_rt/net/
borrowed_read_half.rs

1use crate::{NotEnoughResources, context::Context, 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> {
8    socket: &'s Socket,
9}
10
11impl<'s> BorrowedReadHalf<'s> {
12    pub(super) const fn new(socket: &'s Socket) -> 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    /// # Errors
22    ///
23    /// Returns an error if all `FDS` fd slots are taken.
24    ///
25    /// # Cancel safety
26    ///
27    /// This method is cancel safe.
28    pub async fn readable<
29        E: 'static,
30        const EVENTS: usize,
31        const TASKS: usize,
32        const TASK_SIZE: usize,
33        const ROOT_TASK_SIZE: usize,
34        const TIMERS: usize,
35        const FDS: usize,
36    >(
37        &mut self,
38        ctx: &Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
39    ) -> Result<(), NotEnoughResources> {
40        self.socket
41            .ready(&ctx.storage.io_waiters, ctx.selector, Direction::Read)
42            .await
43    }
44
45    /// Reads into a given buffer without waiting, returns the number of read bytes.
46    ///
47    /// Returns `0` if the stream is closed (or if the buffer is empty).
48    ///
49    /// # Errors
50    ///
51    /// Returns [`Errno::AGAIN`](rustix::io::Errno::AGAIN) if the stream is not readable,
52    /// or an error if the syscall fails.
53    pub fn try_read(&self, buf: &mut [u8]) -> rustix::io::Result<usize> {
54        self.socket.try_recv(buf)
55    }
56}
57
58impl AsyncRead for BorrowedReadHalf<'_> {
59    type Error = NetError;
60
61    fn read<
62        'a,
63        E: 'static,
64        const EVENTS: usize,
65        const TASKS: usize,
66        const TASK_SIZE: usize,
67        const ROOT_TASK_SIZE: usize,
68        const TIMERS: usize,
69        const FDS: usize,
70    >(
71        &'a mut self,
72        ctx: &'a Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
73        buf: &'a mut [u8],
74    ) -> impl Future<Output = Result<usize, NetError>> {
75        self.socket.recv(&ctx.storage.io_waiters, ctx.selector, buf)
76    }
77}