externally_driven_async_rt/net/
udp_socket.rs1use core::net::SocketAddr;
2
3use rustix::net::SocketType;
4
5use crate::{
6 context::Context,
7 net::{address::Address, socket::Socket},
8 state::State,
9};
10
11pub struct UdpSocket {
13 socket: Socket,
14}
15
16impl UdpSocket {
17 pub fn bind(addr: SocketAddr) -> rustix::io::Result<Self> {
19 let socket = Socket::new(addr.family(), SocketType::DGRAM)?;
20 socket.bind(&addr)?;
21 Ok(Self { socket })
22 }
23
24 pub async fn send_to<
26 S: State,
27 const TASKS: usize,
28 const TASK_SIZE: usize,
29 const ROOT_TASK_SIZE: usize,
30 const TIMERS: usize,
31 const FDS: usize,
32 >(
33 &mut self,
34 ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
35 buf: &[u8],
36 addr: SocketAddr,
37 ) -> rustix::io::Result<usize> {
38 self.socket.send_to(ctx, buf, &addr).await
39 }
40
41 pub fn recv_from<
43 'a,
44 'ctx,
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<'ctx, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
54 buf: &'a mut [u8],
55 ) -> impl Future<Output = rustix::io::Result<(usize, SocketAddr)>> {
56 self.socket.recv_from(ctx, buf)
57 }
58
59 pub fn connect(&self, addr: SocketAddr) -> rustix::io::Result<()> {
61 self.socket.connect(&addr)
62 }
63
64 pub fn send<
66 'a,
67 'ctx,
68 S: State,
69 const TASKS: usize,
70 const TASK_SIZE: usize,
71 const ROOT_TASK_SIZE: usize,
72 const TIMERS: usize,
73 const FDS: usize,
74 >(
75 &'a mut self,
76 ctx: &'a Context<'ctx, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
77 buf: &'a [u8],
78 ) -> impl Future<Output = rustix::io::Result<usize>> {
79 self.socket.send(ctx, buf)
80 }
81
82 pub fn recv<
84 'a,
85 'ctx,
86 S: State,
87 const TASKS: usize,
88 const TASK_SIZE: usize,
89 const ROOT_TASK_SIZE: usize,
90 const TIMERS: usize,
91 const FDS: usize,
92 >(
93 &'a mut self,
94 ctx: &'a Context<'ctx, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
95 buf: &'a mut [u8],
96 ) -> impl Future<Output = rustix::io::Result<usize>> {
97 self.socket.recv(ctx, buf)
98 }
99
100 pub fn local_addr(&self) -> rustix::io::Result<SocketAddr> {
102 self.socket.local_addr()
103 }
104}
105
106impl core::fmt::Debug for UdpSocket {
107 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
108 f.write_str("UdpSocket")
109 }
110}