network/fundamentals/
udp.rs

1use smoltcp::{phy::PacketMeta, socket::udp, wire};
2
3use crate::{IpAddress, Port};
4
5#[repr(C)]
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct UdpMetadata {
8    pub remote_address: IpAddress,
9    pub local_address: Option<IpAddress>,
10    pub remote_port: Port,
11    pub meta: PacketMeta,
12}
13
14impl UdpMetadata {
15    pub fn new(
16        remote_address: impl Into<IpAddress>,
17        remote_port: impl Into<Port>,
18        local_address: Option<IpAddress>,
19        meta: PacketMeta,
20    ) -> Self {
21        Self {
22            remote_address: remote_address.into(),
23            local_address,
24            remote_port: remote_port.into(),
25            meta,
26        }
27    }
28
29    pub const fn from_smoltcp(value: &udp::UdpMetadata) -> Self {
30        let local_address = match value.local_address {
31            Some(addr) => Some(IpAddress::from_smoltcp(&addr)),
32            None => None,
33        };
34
35        Self {
36            remote_address: IpAddress::from_smoltcp(&value.endpoint.addr),
37            local_address,
38            remote_port: Port::from_inner(value.endpoint.port),
39            meta: value.meta,
40        }
41    }
42
43    pub const fn to_smoltcp(&self) -> udp::UdpMetadata {
44        let local_address = match &self.local_address {
45            Some(addr) => Some(addr.into_smoltcp()),
46            None => None,
47        };
48
49        udp::UdpMetadata {
50            endpoint: wire::IpEndpoint::new(
51                self.remote_address.into_smoltcp(),
52                self.remote_port.into_inner(),
53            ),
54            local_address,
55            meta: self.meta,
56        }
57    }
58}