use super::{Family, InterfaceBuilder, InterfaceOption, Mapping, Method};
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
pub struct Interface {
pub name: String,
pub auto: bool,
pub allow: Vec<String>,
pub family: Option<Family>,
pub method: Option<Method>,
pub options: Vec<InterfaceOption>,
pub mapping: Option<Mapping>,
}
impl Interface {
pub fn builder(name: impl Into<String>) -> InterfaceBuilder {
InterfaceBuilder::new(name)
}
pub fn edit(&self) -> InterfaceBuilder {
InterfaceBuilder {
name: self.name.clone(),
auto: self.auto,
allow: self.allow.clone(),
family: self.family.clone(),
method: self.method.clone(),
options: self.options.clone(),
mapping: self.mapping.clone(),
}
}
pub fn get_option(&self, key: &str) -> Option<String> {
self.options
.iter()
.find(|opt| opt.name() == key)
.map(|opt| opt.value())
}
pub fn get_options(&self, key: &str) -> Vec<String> {
self.options
.iter()
.filter(|opt| opt.name() == key)
.map(|opt| opt.value())
.collect()
}
}
impl fmt::Display for Interface {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.auto {
writeln!(f, "auto {}", self.name)?;
}
for allow_type in &self.allow {
writeln!(f, "allow-{} {}", allow_type, self.name)?;
}
if let Some(mapping) = &self.mapping {
writeln!(f, "mapping {}", self.name)?;
writeln!(f, " script {}", mapping.script.display())?;
for map in &mapping.maps {
writeln!(f, " map {}", map)?;
}
}
write!(f, "iface {}", self.name)?;
if let Some(family) = &self.family {
write!(f, " {}", family)?;
}
if let Some(method) = &self.method {
write!(f, " {}", method)?;
}
writeln!(f)?;
let mut sorted_options = self.options.clone();
sorted_options.sort_by(|a, b| a.name().cmp(b.name()));
for option in &sorted_options {
writeln!(f, " {}", option)?;
}
Ok(())
}
}