interface_rs/interface/
family.rs

1use std::error::Error;
2use std::fmt;
3use std::str::FromStr;
4
5/// Represents the address family in the `interfaces(5)` file.
6///
7/// The `Family` enum constrains the `family` field to allowed values, ensuring
8/// that only valid address families are used.
9///
10/// # Variants
11///
12/// - `Inet`: Represents the `inet` family (IPv4).
13/// - `Inet6`: Represents the `inet6` family (IPv6).
14/// - `IpX`: Represents the `ipx` family.
15/// - `Can`: Represents the `can` family.
16///
17/// # Examples
18///
19/// Parsing a `Family` from a string:
20///
21/// ```rust
22/// use interface_rs::interface::Family;
23/// use std::str::FromStr;
24///
25/// let family = Family::from_str("inet").unwrap();
26/// assert_eq!(family, Family::Inet);
27/// ```
28#[derive(Debug, Clone, PartialEq)]
29pub enum Family {
30    /// The `inet` address family (IPv4).
31    Inet,
32    /// The `inet6` address family (IPv6).
33    Inet6,
34    /// The `ipx` address family.
35    IpX,
36    /// The `can` address family.
37    Can,
38}
39
40impl fmt::Display for Family {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        let family_str = match self {
43            Family::Inet => "inet",
44            Family::Inet6 => "inet6",
45            Family::IpX => "ipx",
46            Family::Can => "can",
47        };
48        write!(f, "{}", family_str)
49    }
50}
51
52impl FromStr for Family {
53    type Err = FamilyParseError;
54
55    /// Parses a `Family` from a string slice.
56    ///
57    /// # Errors
58    ///
59    /// Returns a `FamilyParseError` if the input string does not match any known family.
60    fn from_str(s: &str) -> Result<Self, Self::Err> {
61        match s {
62            "inet" => Ok(Family::Inet),
63            "inet6" => Ok(Family::Inet6),
64            "ipx" => Ok(Family::IpX),
65            "can" => Ok(Family::Can),
66            _ => Err(FamilyParseError(s.to_string())),
67        }
68    }
69}
70
71/// An error that occurs when parsing a `Family` from a string.
72///
73/// This error is returned when the input string does not correspond to any
74/// known address family.
75#[derive(Debug, Clone)]
76pub struct FamilyParseError(pub String);
77
78impl fmt::Display for FamilyParseError {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        write!(f, "Invalid family: {}", self.0)
81    }
82}
83
84impl Error for FamilyParseError {}