menhera_inet/
inet.rs

1
2use std::str::FromStr;
3use std::fmt::Display;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6pub enum InetError {
7    V4(crate::ipv4::Ipv4Error),
8    V6(crate::ipv6::Ipv6Error),
9    Other,
10}
11
12impl Display for InetError {
13    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14        match self {
15            InetError::V4(e) => write!(f, "IPv4 error: {}", e),
16            InetError::V6(e) => write!(f, "IPv6 error: {}", e),
17            InetError::Other => write!(f, "Other error"),
18        }
19    }
20}
21
22impl std::error::Error for InetError {}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25pub enum InetTarget {
26    V4(crate::ipv4::Ipv4Target),
27    V6(crate::ipv6::Ipv6Target),
28}
29
30impl FromStr for InetTarget {
31    type Err = InetError;
32
33    fn from_str(s: &str) -> Result<Self, Self::Err> {
34        if let Ok(v4) = s.parse() {
35            return Ok(InetTarget::V4(v4));
36        }
37        if let Ok(v6) = s.parse() {
38            return Ok(InetTarget::V6(v6));
39        }
40        Err(InetError::Other)
41    }
42}
43
44impl Display for InetTarget {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        match self {
47            InetTarget::V4(v4) => write!(f, "{}", v4),
48            InetTarget::V6(v6) => write!(f, "{}", v6),
49        }
50    }
51}
52
53impl InetTarget {
54    pub fn ip(&self) -> std::net::IpAddr {
55        match self {
56            InetTarget::V4(v4) => std::net::IpAddr::V4(v4.ip()),
57            InetTarget::V6(v6) => std::net::IpAddr::V6(v6.ip()),
58        }
59    }
60
61    pub fn prefix_len(&self) -> Option<u8> {
62        match self {
63            InetTarget::V4(v4) => v4.prefix_len(),
64            InetTarget::V6(v6) => v6.prefix_len(),
65        }
66    }
67
68    pub fn is_net(&self) -> bool {
69        match self {
70            InetTarget::V4(v4) => v4.is_net(),
71            InetTarget::V6(v6) => v6.is_net(),
72        }
73    }
74
75    pub fn net(&self) -> Option<ipnet::IpNet> {
76        match self {
77            InetTarget::V4(v4) => v4.net().map(|n| n.into()),
78            InetTarget::V6(v6) => v6.net().map(|n| n.into()),
79        }
80    }
81}