externally_driven_async_rt/net/
udp_socket.rs1use core::net::SocketAddr;
2
3use rustix::{
4 io::Errno,
5 net::{SocketType, addr::SocketAddrArg},
6};
7
8use crate::{context::Context, net::socket::Socket, state::State};
9
10#[must_use]
12pub struct UdpSocket {
13 socket: Socket,
14}
15
16impl UdpSocket {
17 pub fn bind(addr: SocketAddr) -> rustix::io::Result<Self> {
23 let socket = Socket::new(addr.as_any().address_family(), SocketType::DGRAM)?;
24 socket.bind(&addr)?;
25 Ok(Self { socket })
26 }
27
28 pub async fn send_to<
34 S: State,
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 &mut self,
42 ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
43 buf: &[u8],
44 addr: SocketAddr,
45 ) -> rustix::io::Result<usize> {
46 self.socket.send_to(ctx, buf, &addr).await
47 }
48
49 pub fn recv_from<
55 'a,
56 S: State,
57 const TASKS: usize,
58 const TASK_SIZE: usize,
59 const ROOT_TASK_SIZE: usize,
60 const TIMERS: usize,
61 const FDS: usize,
62 >(
63 &'a mut self,
64 ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
65 buf: &'a mut [u8],
66 ) -> impl Future<Output = rustix::io::Result<(usize, SocketAddr)>> {
67 let recv = self.socket.recv_from(ctx, buf);
68 async move {
69 let (len, addr) = recv.await?;
70 Ok((len, addr.ok_or(Errno::AFNOSUPPORT)?.try_into()?))
71 }
72 }
73
74 pub fn connect(&self, addr: SocketAddr) -> rustix::io::Result<()> {
80 self.socket.connect(&addr)
81 }
82
83 pub fn send<
89 'a,
90 S: State,
91 const TASKS: usize,
92 const TASK_SIZE: usize,
93 const ROOT_TASK_SIZE: usize,
94 const TIMERS: usize,
95 const FDS: usize,
96 >(
97 &'a mut self,
98 ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
99 buf: &'a [u8],
100 ) -> impl Future<Output = rustix::io::Result<usize>> {
101 self.socket.send(ctx, buf)
102 }
103
104 pub fn recv<
110 'a,
111 S: State,
112 const TASKS: usize,
113 const TASK_SIZE: usize,
114 const ROOT_TASK_SIZE: usize,
115 const TIMERS: usize,
116 const FDS: usize,
117 >(
118 &'a mut self,
119 ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
120 buf: &'a mut [u8],
121 ) -> impl Future<Output = rustix::io::Result<usize>> {
122 self.socket.recv(ctx, buf)
123 }
124
125 pub fn local_addr(&self) -> rustix::io::Result<SocketAddr> {
131 self.socket.local_addr()
132 }
133}
134
135impl core::fmt::Debug for UdpSocket {
136 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
137 f.write_str("UdpSocket")
138 }
139}