externally_driven_async_rt/net/
tcp_stream.rs1use 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#[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 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 pub fn shutdown(&self, how: Shutdown) -> rustix::io::Result<()> {
55 self.socket.shutdown(how)
56 }
57
58 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 pub fn local_addr(&self) -> rustix::io::Result<SocketAddr> {
83 self.socket.local_addr()
84 }
85
86 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 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}