Skip to main content

externally_driven_async_rt/net/
borrowed_write_half.rs

1use crate::{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, 'sel, const FDS: usize> {
8    socket: &'s Socket<'sel, FDS>,
9}
10
11impl<'s, 'sel, const FDS: usize> BorrowedWriteHalf<'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 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(&mut self) {
25        self.socket.ready(Direction::Write).await;
26    }
27
28    /// Writes from a given buffer without waiting, returns the number of written bytes.
29    ///
30    /// # Errors
31    ///
32    /// Returns [`Errno::AGAIN`](rustix::io::Errno::AGAIN) if the stream is not writable,
33    /// or an error if the syscall fails.
34    pub fn try_write(&self, buf: &[u8]) -> rustix::io::Result<usize> {
35        self.socket.try_send(buf)
36    }
37}
38
39impl<const FDS: usize> AsyncWrite for BorrowedWriteHalf<'_, '_, FDS> {
40    type Error = NetError;
41
42    fn write<'a>(&'a mut self, buf: &'a [u8]) -> impl Future<Output = Result<usize, NetError>> {
43        self.socket.send(buf)
44    }
45
46    fn flush(&mut self) -> impl Future<Output = Result<(), NetError>> {
47        core::future::ready(Ok(()))
48    }
49}