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    net::{BorrowedReadHalf, BorrowedWriteHalf, socket::Socket},
9    state::State,
10};
11
12/// A TCP stream.
13#[must_use]
14pub struct TcpStream {
15    socket: Socket,
16}
17
18impl TcpStream {
19    pub(crate) 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.
28    ///
29    /// # Cancel safety
30    ///
31    /// This method is cancel safe.
32    pub async fn connect<
33        S: State,
34        const TASKS: usize,
35        const TASK_SIZE: usize,
36        const ROOT_TASK_SIZE: usize,
37        const TIMERS: usize,
38        const FDS: usize,
39    >(
40        ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
41        addr: SocketAddr,
42    ) -> rustix::io::Result<Self> {
43        let socket = Socket::connect_stream(ctx, &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(&mut self) -> (BorrowedReadHalf<'_>, BorrowedWriteHalf<'_>) {
100        (
101            BorrowedReadHalf::new(&self.socket),
102            BorrowedWriteHalf::new(&self.socket),
103        )
104    }
105}
106
107impl AsyncRead for TcpStream {
108    type Error = Errno;
109
110    fn read<
111        'a,
112        S: State,
113        const TASKS: usize,
114        const TASK_SIZE: usize,
115        const ROOT_TASK_SIZE: usize,
116        const TIMERS: usize,
117        const FDS: usize,
118    >(
119        &'a mut self,
120        ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
121        buf: &'a mut [u8],
122    ) -> impl Future<Output = rustix::io::Result<usize>> {
123        self.socket.read(ctx, buf)
124    }
125}
126
127impl AsyncWrite for TcpStream {
128    type Error = Errno;
129
130    fn write<
131        'a,
132        S: State,
133        const TASKS: usize,
134        const TASK_SIZE: usize,
135        const ROOT_TASK_SIZE: usize,
136        const TIMERS: usize,
137        const FDS: usize,
138    >(
139        &'a mut self,
140        ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
141        buf: &'a [u8],
142    ) -> impl Future<Output = rustix::io::Result<usize>> {
143        self.socket.write(ctx, buf)
144    }
145
146    fn flush<
147        'a,
148        S: State,
149        const TASKS: usize,
150        const TASK_SIZE: usize,
151        const ROOT_TASK_SIZE: usize,
152        const TIMERS: usize,
153        const FDS: usize,
154    >(
155        &'a mut self,
156        _ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
157    ) -> impl Future<Output = rustix::io::Result<()>> {
158        core::future::ready(Ok(()))
159    }
160}
161
162impl core::fmt::Debug for TcpStream {
163    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
164        f.write_str("TcpStream")
165    }
166}