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;
9
10use super::{NetError, socket::Socket};
11
12#[must_use]
14pub struct UdpSocket {
15 socket: Socket,
16}
17
18impl UdpSocket {
19 pub fn bind(addr: SocketAddr) -> rustix::io::Result<Self> {
25 let socket = Socket::new(addr.as_any().address_family(), SocketType::DGRAM)?;
26 socket.bind(&addr)?;
27 Ok(Self { socket })
28 }
29
30 pub async fn send_to<
40 E: 'static,
41 const EVENTS: usize,
42 const TASKS: usize,
43 const TASK_SIZE: usize,
44 const ROOT_TASK_SIZE: usize,
45 const TIMERS: usize,
46 const FDS: usize,
47 >(
48 &mut self,
49 ctx: &Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
50 buf: &[u8],
51 addr: SocketAddr,
52 ) -> Result<usize, NetError> {
53 self.socket
54 .send_to(&ctx.storage.io_waiters, ctx.selector, buf, &addr)
55 .await
56 }
57
58 pub fn recv_from<
68 'a,
69 E: 'static,
70 const EVENTS: usize,
71 const TASKS: usize,
72 const TASK_SIZE: usize,
73 const ROOT_TASK_SIZE: usize,
74 const TIMERS: usize,
75 const FDS: usize,
76 >(
77 &'a mut self,
78 ctx: &'a Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
79 buf: &'a mut [u8],
80 ) -> impl Future<Output = Result<(usize, SocketAddr), NetError>> {
81 let recv = self
82 .socket
83 .recv_from(&ctx.storage.io_waiters, ctx.selector, buf);
84 async move {
85 let (len, addr) = recv.await?;
86 Ok((len, addr.ok_or(Errno::AFNOSUPPORT)?.try_into()?))
87 }
88 }
89
90 pub fn connect(&self, addr: SocketAddr) -> rustix::io::Result<()> {
96 self.socket.connect(&addr)
97 }
98
99 pub fn send<
109 'a,
110 E: 'static,
111 const EVENTS: usize,
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<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
120 buf: &'a [u8],
121 ) -> impl Future<Output = Result<usize, NetError>> {
122 self.socket.send(&ctx.storage.io_waiters, ctx.selector, buf)
123 }
124
125 pub fn recv<
135 'a,
136 E: 'static,
137 const EVENTS: usize,
138 const TASKS: usize,
139 const TASK_SIZE: usize,
140 const ROOT_TASK_SIZE: usize,
141 const TIMERS: usize,
142 const FDS: usize,
143 >(
144 &'a mut self,
145 ctx: &'a Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
146 buf: &'a mut [u8],
147 ) -> impl Future<Output = Result<usize, NetError>> {
148 self.socket.recv(&ctx.storage.io_waiters, ctx.selector, buf)
149 }
150
151 pub fn local_addr(&self) -> rustix::io::Result<SocketAddr> {
157 self.socket.local_addr()
158 }
159}