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 {
15    socket: Socket,
16}
17
18impl TcpStream {
19    pub(super) const fn new(socket: Socket) -> 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        const FDS: usize,
40    >(
41        ctx: &Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
42        addr: SocketAddr,
43    ) -> Result<Self, NetError> {
44        let socket = Socket::connect_stream(&ctx.storage.io_waiters, ctx.selector, &addr).await?;
45        Ok(Self { socket })
46    }
47
48    /// Shuts down the connection (which also impacts potentially existing read/write halves).
49    ///
50    /// The underlying file descriptor stays open until this value is dropped.
51    ///
52    /// # Errors
53    ///
54    /// Returns an error if a syscall fails.
55    pub fn shutdown(&self, how: Shutdown) -> rustix::io::Result<()> {
56        self.socket.shutdown(how)
57    }
58
59    /// Enables TCP keepalive.
60    ///
61    /// Once the connection is idle for `idle`, a probe is sent every `interval`, and the
62    /// connection is considered dead after `count` unanswered probes. On Linux the same total
63    /// (`idle + interval * count`) also limits how long sent data may stay unacknowledged
64    /// (`TCP_USER_TIMEOUT`).
65    ///
66    /// # Errors
67    ///
68    /// Returns an error if a syscall fails, or if the total doesn't fit into `TCP_USER_TIMEOUT`.
69    pub fn set_keepalive(
70        &self,
71        idle: Duration,
72        interval: Duration,
73        count: u32,
74    ) -> rustix::io::Result<()> {
75        self.socket.set_keepalive(idle, interval, count)
76    }
77
78    /// Returns local address.
79    ///
80    /// # Errors
81    ///
82    /// Returns an error if a syscall fails.
83    pub fn local_addr(&self) -> rustix::io::Result<SocketAddr> {
84        self.socket.local_addr()
85    }
86
87    /// Returns peer address.
88    ///
89    /// # Errors
90    ///
91    /// Returns an error if a syscall fails.
92    pub fn peer_addr(&self) -> rustix::io::Result<SocketAddr> {
93        self.socket
94            .peer_addr()?
95            .ok_or(Errno::AFNOSUPPORT)?
96            .try_into()
97    }
98
99    /// Splits the [`TcpStream`] into two halves: reader and writer.
100    pub const fn split(&mut self) -> (BorrowedReadHalf<'_>, BorrowedWriteHalf<'_>) {
101        (
102            BorrowedReadHalf::new(&self.socket),
103            BorrowedWriteHalf::new(&self.socket),
104        )
105    }
106}
107
108impl AsyncRead for TcpStream {
109    type Error = NetError;
110
111    fn read<
112        'a,
113        E: 'static,
114        const EVENTS: usize,
115        const TASKS: usize,
116        const TASK_SIZE: usize,
117        const ROOT_TASK_SIZE: usize,
118        const TIMERS: usize,
119        const FDS: usize,
120    >(
121        &'a mut self,
122        ctx: &'a Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
123        buf: &'a mut [u8],
124    ) -> impl Future<Output = Result<usize, NetError>> {
125        self.socket.recv(&ctx.storage.io_waiters, ctx.selector, buf)
126    }
127}
128
129impl AsyncWrite for TcpStream {
130    type Error = NetError;
131
132    fn write<
133        'a,
134        E: 'static,
135        const EVENTS: usize,
136        const TASKS: usize,
137        const TASK_SIZE: usize,
138        const ROOT_TASK_SIZE: usize,
139        const TIMERS: usize,
140        const FDS: usize,
141    >(
142        &'a mut self,
143        ctx: &'a Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
144        buf: &'a [u8],
145    ) -> impl Future<Output = Result<usize, NetError>> {
146        self.socket.send(&ctx.storage.io_waiters, ctx.selector, buf)
147    }
148
149    fn flush<
150        'a,
151        E: 'static,
152        const EVENTS: usize,
153        const TASKS: usize,
154        const TASK_SIZE: usize,
155        const ROOT_TASK_SIZE: usize,
156        const TIMERS: usize,
157        const FDS: usize,
158    >(
159        &'a mut self,
160        _ctx: &'a Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
161    ) -> impl Future<Output = Result<(), NetError>> {
162        core::future::ready(Ok(()))
163    }
164}