Skip to main content

arcbox_helper/validate/
bridge_iface.rs

1use std::str::FromStr;
2
3/// A validated bridge interface name (e.g. `bridge100`).
4///
5/// Guarantees: matches `^bridge[0-9]+$` with a number that fits in `u32`.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct BridgeIface(String);
8
9impl BridgeIface {
10    pub fn as_str(&self) -> &str {
11        &self.0
12    }
13}
14
15impl FromStr for BridgeIface {
16    type Err = String;
17
18    fn from_str(s: &str) -> Result<Self, Self::Err> {
19        let suffix = s
20            .strip_prefix("bridge")
21            .ok_or_else(|| format!("interface '{s}' must start with 'bridge'"))?;
22
23        if suffix.is_empty() || !suffix.bytes().all(|b| b.is_ascii_digit()) {
24            return Err(format!(
25                "interface '{s}' must match bridge<N> (e.g. bridge100)"
26            ));
27        }
28
29        let _n: u32 = suffix
30            .parse()
31            .map_err(|_| format!("interface '{s}' has invalid bridge number (too large)"))?;
32
33        Ok(Self(s.to_owned()))
34    }
35}
36
37impl std::fmt::Display for BridgeIface {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        f.write_str(&self.0)
40    }
41}