network/fundamentals/
route.rs

1use core::time::Duration;
2
3use crate::{IpAddress, IpCidr};
4
5#[repr(C)]
6#[derive(Default, Clone, PartialEq, Eq)]
7pub struct Route {
8    pub cidr: IpCidr,
9    pub via_router: IpAddress,
10    pub preferred_until: Option<Duration>,
11    pub expires_at: Option<Duration>,
12}
13
14impl Route {
15    pub const fn new_default_ipv4(via_router: [u8; 4]) -> Self {
16        Self {
17            cidr: IpCidr::new_ipv4([0, 0, 0, 0], 0),
18            via_router: IpAddress::new_ipv4(via_router),
19            preferred_until: None,
20            expires_at: None,
21        }
22    }
23
24    pub const fn new_default_ipv6(via_router: [u16; 8]) -> Self {
25        Self {
26            cidr: IpCidr::new_ipv6([0, 0, 0, 0, 0, 0, 0, 0], 0),
27            via_router: IpAddress::new_ipv6(via_router),
28            preferred_until: None,
29            expires_at: None,
30        }
31    }
32
33    pub const fn from_smoltcp(route: smoltcp::iface::Route) -> Self {
34        let preferred_until = if let Some(dur) = route.preferred_until {
35            Some(Duration::from_micros(dur.micros() as u64))
36        } else {
37            None
38        };
39
40        let expires_at = if let Some(dur) = route.expires_at {
41            Some(Duration::from_micros(dur.micros() as u64))
42        } else {
43            None
44        };
45
46        Self {
47            cidr: IpCidr::from_smoltcp(&route.cidr),
48            via_router: IpAddress::from_smoltcp(&route.via_router),
49            preferred_until,
50            expires_at,
51        }
52    }
53
54    pub fn into_smoltcp(&self) -> smoltcp::iface::Route {
55        let preferred_until = self
56            .preferred_until
57            .map(|dur| smoltcp::time::Instant::from_micros(dur.as_micros() as i64));
58
59        let expires_at = self
60            .expires_at
61            .map(|dur| smoltcp::time::Instant::from_micros(dur.as_micros() as i64));
62
63        smoltcp::iface::Route {
64            cidr: self.cidr.into_smoltcp(),
65            via_router: self.via_router.into_smoltcp(),
66            preferred_until,
67            expires_at,
68        }
69    }
70}