batman-robin 1.2.1

Rust library and CLI tool for interacting with the BATMAN-adv kernel module for mesh networking
Documentation
/// Selects a network interface either by interface name or by ifindex.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct InterfaceSelector {
    /// Selects the interface by name (for example, `"wlan0"`).
    pub name: Option<String>,
    /// Selects the interface by Linux interface index.
    pub ifindex: Option<u32>,
}

impl InterfaceSelector {
    /// Creates an empty selector.
    pub fn new() -> Self {
        Self {
            name: None,
            ifindex: None,
        }
    }

    /// Creates a selector from an interface name.
    pub fn with_name(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            ifindex: None,
        }
    }

    /// Creates a selector from an interface index.
    pub const fn with_ifindex(ifindex: u32) -> Self {
        Self {
            name: None,
            ifindex: Some(ifindex),
        }
    }
}

impl validator::Validate for InterfaceSelector {
    fn validate(&self) -> Result<(), validator::ValidationErrors> {
        let mut errors = validator::ValidationErrors::new();

        if self.name.is_none() && self.ifindex.is_none() {
            errors.add(
                "interface_selector",
                validator::ValidationError {
                    code: std::borrow::Cow::from("at_least_one_field"),
                    message: Some(std::borrow::Cow::from(
                        "At least one of 'name' or 'ifindex' must be set",
                    )),
                    params: std::collections::HashMap::new(),
                },
            );
        }

        if let Some(name) = &self.name
            && name.trim().is_empty()
        {
            errors.add(
                "name",
                validator::ValidationError {
                    code: std::borrow::Cow::from("empty_name"),
                    message: Some(std::borrow::Cow::from(
                        "Interface selector name cannot be empty",
                    )),
                    params: std::collections::HashMap::new(),
                },
            );
        }

        if let Some(ifindex) = self.ifindex
            && ifindex == 0
        {
            errors.add(
                "ifindex",
                validator::ValidationError {
                    code: std::borrow::Cow::from("invalid_ifindex"),
                    message: Some(std::borrow::Cow::from(
                        "Interface selector ifindex must be greater than 0",
                    )),
                    params: std::collections::HashMap::new(),
                },
            );
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}