Skip to main content

arcbox_helper/validate/
subnet.rs

1use std::str::FromStr;
2
3use ipnetwork::Ipv4Network;
4
5/// A validated private CIDR subnet (e.g. `10.0.0.0/8`).
6///
7/// Guarantees:
8/// - Valid IPv4 CIDR notation with explicit prefix
9/// - No non-zero host bits
10/// - IP is in a private range (10/8, 172.16/12, 192.168/16)
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct Subnet(Ipv4Network);
13
14impl Subnet {
15    pub fn as_str(&self) -> String {
16        self.0.to_string()
17    }
18
19    pub fn network(&self) -> &Ipv4Network {
20        &self.0
21    }
22}
23
24impl FromStr for Subnet {
25    type Err = String;
26
27    fn from_str(s: &str) -> Result<Self, Self::Err> {
28        if !s.contains('/') {
29            return Err(format!("invalid CIDR: missing '/' in '{s}'"));
30        }
31
32        let net: Ipv4Network = s.parse().map_err(|e| format!("invalid CIDR '{s}': {e}"))?;
33
34        if net.ip() != net.network() {
35            return Err(format!(
36                "CIDR '{s}' has non-zero host bits (did you mean {}/{}?)",
37                net.network(),
38                net.prefix()
39            ));
40        }
41
42        if !net.ip().is_private() {
43            return Err(format!(
44                "subnet {s} is not in a private range (10/8, 172.16/12, 192.168/16)"
45            ));
46        }
47
48        Ok(Self(net))
49    }
50}
51
52impl std::fmt::Display for Subnet {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        write!(f, "{}", self.0)
55    }
56}