Skip to main content

externally_driven_async_rt/net/
borrowed_write_half.rs

1use crate::{
2    context::Context, io::AsyncWrite, net::socket::Socket, selector::Direction, state::State,
3};
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(crate) 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    /// # Cancel safety
22    ///
23    /// This method is cancel safe.
24    pub async fn writable<
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::Write).await;
36    }
37
38    /// Writes from a given buffer without waiting, returns the number of written bytes.
39    ///
40    /// # Errors
41    ///
42    /// Returns [`Errno::AGAIN`](rustix::io::Errno::AGAIN) if the stream is not writable,
43    /// or an error if the syscall fails.
44    pub fn try_write(&self, buf: &[u8]) -> rustix::io::Result<usize> {
45        self.socket.try_write(buf)
46    }
47}
48
49impl AsyncWrite for BorrowedWriteHalf<'_> {
50    type Error = rustix::io::Errno;
51
52    fn write<
53        'a,
54        S: State,
55        const TASKS: usize,
56        const TASK_SIZE: usize,
57        const ROOT_TASK_SIZE: usize,
58        const TIMERS: usize,
59        const FDS: usize,
60    >(
61        &'a mut self,
62        ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
63        buf: &'a [u8],
64    ) -> impl Future<Output = rustix::io::Result<usize>> {
65        self.socket.write(ctx, buf)
66    }
67
68    fn flush<
69        'a,
70        S: State,
71        const TASKS: usize,
72        const TASK_SIZE: usize,
73        const ROOT_TASK_SIZE: usize,
74        const TIMERS: usize,
75        const FDS: usize,
76    >(
77        &'a mut self,
78        _ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
79    ) -> impl Future<Output = rustix::io::Result<()>> {
80        core::future::ready(Ok(()))
81    }
82}
83
84impl core::fmt::Debug for BorrowedWriteHalf<'_> {
85    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
86        f.write_str("BorrowedWriteHalf")
87    }
88}