Skip to main content

externally_driven_async_rt/net/
tcp_stream.rs

1use core::{net::SocketAddr, time::Duration};
2
3use rustix::{io::Errno, net::Shutdown};
4
5use crate::{
6    context::Context,
7    io::{AsyncRead, AsyncWrite},
8};
9
10use super::{BorrowedReadHalf, BorrowedWriteHalf, NetError, socket::Socket};
11
12/// A TCP stream.
13#[must_use]
14pub struct TcpStream<'sel, const FDS: usize> {
15    socket: Socket<'sel, FDS>,
16}
17
18impl<'sel, const FDS: usize> TcpStream<'sel, FDS> {
19    pub(super) const fn new(socket: Socket<'sel, FDS>) -> Self {
20        Self { socket }
21    }
22
23    /// Connects to a given address.
24    ///
25    /// # Errors
26    ///
27    /// Returns an error if a syscall fails or if all `FDS` fd slots are taken.
28    ///
29    /// # Cancel safety
30    ///
31    /// This method is cancel safe.
32    pub async fn connect<
33        E: 'static,
34        const EVENTS: usize,
35        const TASKS: usize,
36        const TASK_SIZE: usize,
37        const ROOT_TASK_SIZE: usize,
38        const TIMERS: usize,
39    >(
40        ctx: &Context<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
41        addr: SocketAddr,
42    ) -> Result<Self, NetError> {
43        let socket = Socket::connect_stream(&ctx.storage.io_waiters, ctx.selector, &addr).await?;
44        Ok(Self { socket })
45    }
46
47    /// Shuts down the connection (which also impacts potentially existing read/write halves).
48    ///
49    /// The underlying file descriptor stays open until this value is dropped.
50    ///
51    /// # Errors
52    ///
53    /// Returns an error if a syscall fails.
54    pub fn shutdown(&self, how: Shutdown) -> rustix::io::Result<()> {
55        self.socket.shutdown(how)
56    }
57
58    /// Enables TCP keepalive.
59    ///
60    /// Once the connection is idle for `idle`, a probe is sent every `interval`, and the
61    /// connection is considered dead after `count` unanswered probes. On Linux the same total
62    /// (`idle + interval * count`) also limits how long sent data may stay unacknowledged
63    /// (`TCP_USER_TIMEOUT`).
64    ///
65    /// # Errors
66    ///
67    /// Returns an error if a syscall fails, or if the total doesn't fit into `TCP_USER_TIMEOUT`.
68    pub fn set_keepalive(
69        &self,
70        idle: Duration,
71        interval: Duration,
72        count: u32,
73    ) -> rustix::io::Result<()> {
74        self.socket.set_keepalive(idle, interval, count)
75    }
76
77    /// Returns local address.
78    ///
79    /// # Errors
80    ///
81    /// Returns an error if a syscall fails.
82    pub fn local_addr(&self) -> rustix::io::Result<SocketAddr> {
83        self.socket.local_addr()
84    }
85
86    /// Returns peer address.
87    ///
88    /// # Errors
89    ///
90    /// Returns an error if a syscall fails.
91    pub fn peer_addr(&self) -> rustix::io::Result<SocketAddr> {
92        self.socket
93            .peer_addr()?
94            .ok_or(Errno::AFNOSUPPORT)?
95            .try_into()
96    }
97
98    /// Splits the [`TcpStream`] into two halves: reader and writer.
99    pub const fn split(
100        &mut self,
101    ) -> (
102        BorrowedReadHalf<'_, 'sel, FDS>,
103        BorrowedWriteHalf<'_, 'sel, FDS>,
104    ) {
105        (
106            BorrowedReadHalf::new(&self.socket),
107            BorrowedWriteHalf::new(&self.socket),
108        )
109    }
110}
111
112impl<const FDS: usize> AsyncRead for TcpStream<'_, FDS> {
113    type Error = NetError;
114
115    fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> impl Future<Output = Result<usize, NetError>> {
116        self.socket.recv(buf)
117    }
118}
119
120impl<const FDS: usize> AsyncWrite for TcpStream<'_, FDS> {
121    type Error = NetError;
122
123    fn write<'a>(&'a mut self, buf: &'a [u8]) -> impl Future<Output = Result<usize, NetError>> {
124        self.socket.send(buf)
125    }
126
127    fn flush(&mut self) -> impl Future<Output = Result<(), NetError>> {
128        core::future::ready(Ok(()))
129    }
130}