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<
38 S: State,
39 const TASKS: usize,
40 const TASK_SIZE: usize,
41 const ROOT_TASK_SIZE: usize,
42 const TIMERS: usize,
43 const FDS: usize,
44 >(
45 &mut self,
46 ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
47 buf: &[u8],
48 addr: SocketAddr,
49 ) -> rustix::io::Result<usize> {
50 self.socket.send_to(ctx, buf, &addr).await
51 }
52
53 pub fn recv_from<
63 'a,
64 S: State,
65 const TASKS: usize,
66 const TASK_SIZE: usize,
67 const ROOT_TASK_SIZE: usize,
68 const TIMERS: usize,
69 const FDS: usize,
70 >(
71 &'a mut self,
72 ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
73 buf: &'a mut [u8],
74 ) -> impl Future<Output = rustix::io::Result<(usize, SocketAddr)>> {
75 let recv = self.socket.recv_from(ctx, buf);
76 async move {
77 let (len, addr) = recv.await?;
78 Ok((len, addr.ok_or(Errno::AFNOSUPPORT)?.try_into()?))
79 }
80 }
81
82 pub fn connect(&self, addr: SocketAddr) -> rustix::io::Result<()> {
88 self.socket.connect(&addr)
89 }
90
91 pub fn send<
101 'a,
102 S: State,
103 const TASKS: usize,
104 const TASK_SIZE: usize,
105 const ROOT_TASK_SIZE: usize,
106 const TIMERS: usize,
107 const FDS: usize,
108 >(
109 &'a mut self,
110 ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
111 buf: &'a [u8],
112 ) -> impl Future<Output = rustix::io::Result<usize>> {
113 self.socket.send(ctx, buf)
114 }
115
116 pub fn recv<
126 'a,
127 S: State,
128 const TASKS: usize,
129 const TASK_SIZE: usize,
130 const ROOT_TASK_SIZE: usize,
131 const TIMERS: usize,
132 const FDS: usize,
133 >(
134 &'a mut self,
135 ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
136 buf: &'a mut [u8],
137 ) -> impl Future<Output = rustix::io::Result<usize>> {
138 self.socket.recv(ctx, buf)
139 }
140
141 pub fn local_addr(&self) -> rustix::io::Result<SocketAddr> {
147 self.socket.local_addr()
148 }
149}
150
151impl core::fmt::Debug for UdpSocket {
152 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
153 f.write_str("UdpSocket")
154 }
155}