Skip to main content

externally_driven_async_rt/net/
borrowed_read_half.rs

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