externally_driven_async_rt/net/
tcp_stream.rs1use core::net::SocketAddr;
2
3use rustix::{io::Errno, net::Shutdown};
4
5use crate::{
6 context::Context,
7 net::{BorrowedReadHalf, BorrowedWriteHalf, socket::Socket},
8 state::State,
9};
10
11#[must_use]
13pub struct TcpStream {
14 socket: Socket,
15}
16
17impl TcpStream {
18 pub(crate) const fn new(socket: Socket) -> Self {
19 Self { socket }
20 }
21
22 pub async fn connect<
28 S: State,
29 const TASKS: usize,
30 const TASK_SIZE: usize,
31 const ROOT_TASK_SIZE: usize,
32 const TIMERS: usize,
33 const FDS: usize,
34 >(
35 ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
36 addr: SocketAddr,
37 ) -> rustix::io::Result<Self> {
38 let socket = Socket::connect_stream(ctx, &addr).await?;
39 Ok(Self { socket })
40 }
41
42 pub fn read<
44 'a,
45 S: State,
46 const TASKS: usize,
47 const TASK_SIZE: usize,
48 const ROOT_TASK_SIZE: usize,
49 const TIMERS: usize,
50 const FDS: usize,
51 >(
52 &'a mut self,
53 ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
54 buf: &'a mut [u8],
55 ) -> impl Future<Output = rustix::io::Result<usize>> {
56 self.socket.read(ctx, buf)
57 }
58
59 pub fn write<
61 'a,
62 S: State,
63 const TASKS: usize,
64 const TASK_SIZE: usize,
65 const ROOT_TASK_SIZE: usize,
66 const TIMERS: usize,
67 const FDS: usize,
68 >(
69 &'a mut self,
70 ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
71 buf: &'a [u8],
72 ) -> impl Future<Output = rustix::io::Result<usize>> {
73 self.socket.write(ctx, buf)
74 }
75
76 pub fn shutdown(&self, how: Shutdown) -> rustix::io::Result<()> {
84 self.socket.shutdown(how)
85 }
86
87 pub fn local_addr(&self) -> rustix::io::Result<SocketAddr> {
93 self.socket.local_addr()
94 }
95
96 pub fn peer_addr(&self) -> rustix::io::Result<SocketAddr> {
102 self.socket
103 .peer_addr()?
104 .ok_or(Errno::AFNOSUPPORT)?
105 .try_into()
106 }
107
108 pub const fn split(&mut self) -> (BorrowedReadHalf<'_>, BorrowedWriteHalf<'_>) {
110 (
111 BorrowedReadHalf::new(&self.socket),
112 BorrowedWriteHalf::new(&self.socket),
113 )
114 }
115}
116
117impl core::fmt::Debug for TcpStream {
118 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
119 f.write_str("TcpStream")
120 }
121}