Skip to main content

externally_driven_async_rt/net/
borrowed_write_half.rs

1use crate::{NotEnoughResources, context::Context, io::AsyncWrite, selector::Direction};
2
3use super::{NetError, socket::Socket};
4
5/// Write half of a TCP/Unix stream.
6#[must_use]
7pub struct BorrowedWriteHalf<'s> {
8    socket: &'s Socket,
9}
10
11impl<'s> BorrowedWriteHalf<'s> {
12    pub(super) const fn new(socket: &'s Socket) -> Self {
13        Self { socket }
14    }
15
16    /// Waits until the stream is writable.
17    ///
18    /// The stream may still turn out to be not writable, so [`try_write`](Self::try_write)
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 writable<
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::Write)
42            .await
43    }
44
45    /// Writes from a given buffer without waiting, returns the number of written bytes.
46    ///
47    /// # Errors
48    ///
49    /// Returns [`Errno::AGAIN`](rustix::io::Errno::AGAIN) if the stream is not writable,
50    /// or an error if the syscall fails.
51    pub fn try_write(&self, buf: &[u8]) -> rustix::io::Result<usize> {
52        self.socket.try_send(buf)
53    }
54}
55
56impl AsyncWrite for BorrowedWriteHalf<'_> {
57    type Error = NetError;
58
59    fn write<
60        'a,
61        E: 'static,
62        const EVENTS: usize,
63        const TASKS: usize,
64        const TASK_SIZE: usize,
65        const ROOT_TASK_SIZE: usize,
66        const TIMERS: usize,
67        const FDS: usize,
68    >(
69        &'a mut self,
70        ctx: &'a Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
71        buf: &'a [u8],
72    ) -> impl Future<Output = Result<usize, NetError>> {
73        self.socket.send(&ctx.storage.io_waiters, ctx.selector, buf)
74    }
75
76    fn flush<
77        'a,
78        E: 'static,
79        const EVENTS: usize,
80        const TASKS: usize,
81        const TASK_SIZE: usize,
82        const ROOT_TASK_SIZE: usize,
83        const TIMERS: usize,
84        const FDS: usize,
85    >(
86        &'a mut self,
87        _ctx: &'a Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
88    ) -> impl Future<Output = Result<(), NetError>> {
89        core::future::ready(Ok(()))
90    }
91}