externally_driven_async_rt/net/
unix_stream.rs1use rustix::net::{Shutdown, SocketAddrUnix};
2
3use crate::{
4 context::Context,
5 io::{AsyncRead, AsyncWrite},
6};
7
8use super::{BorrowedReadHalf, BorrowedWriteHalf, NetError, socket::Socket};
9
10#[must_use]
12pub struct UnixStream<'sel, const FDS: usize> {
13 socket: Socket<'sel, FDS>,
14}
15
16impl<'sel, const FDS: usize> UnixStream<'sel, FDS> {
17 pub(super) const fn new(socket: Socket<'sel, FDS>) -> Self {
18 Self { socket }
19 }
20
21 pub async fn connect<
31 E: 'static,
32 const EVENTS: usize,
33 const TASKS: usize,
34 const TASK_SIZE: usize,
35 const ROOT_TASK_SIZE: usize,
36 const TIMERS: usize,
37 >(
38 ctx: &Context<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
39 addr: &SocketAddrUnix,
40 ) -> Result<Self, NetError> {
41 let socket = Socket::connect_stream(&ctx.storage.io_waiters, ctx.selector, addr).await?;
42 Ok(Self { socket })
43 }
44
45 pub fn shutdown(&self, how: Shutdown) -> rustix::io::Result<()> {
53 self.socket.shutdown(how)
54 }
55
56 pub fn local_addr(&self) -> rustix::io::Result<SocketAddrUnix> {
62 self.socket.local_addr()
63 }
64
65 pub fn peer_addr(&self) -> rustix::io::Result<SocketAddrUnix> {
71 self.socket
72 .peer_addr()?
73 .map_or_else(|| SocketAddrUnix::new(""), TryInto::try_into)
74 }
75
76 pub const fn split(
78 &mut self,
79 ) -> (
80 BorrowedReadHalf<'_, 'sel, FDS>,
81 BorrowedWriteHalf<'_, 'sel, FDS>,
82 ) {
83 (
84 BorrowedReadHalf::new(&self.socket),
85 BorrowedWriteHalf::new(&self.socket),
86 )
87 }
88}
89
90impl<const FDS: usize> AsyncRead for UnixStream<'_, FDS> {
91 type Error = NetError;
92
93 fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> impl Future<Output = Result<usize, NetError>> {
94 self.socket.recv(buf)
95 }
96}
97
98impl<const FDS: usize> AsyncWrite for UnixStream<'_, FDS> {
99 type Error = NetError;
100
101 fn write<'a>(&'a mut self, buf: &'a [u8]) -> impl Future<Output = Result<usize, NetError>> {
102 self.socket.send(buf)
103 }
104
105 fn flush(&mut self) -> impl Future<Output = Result<(), NetError>> {
106 core::future::ready(Ok(()))
107 }
108}