interface_rs/interface/
family.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::error::Error;
use std::fmt;
use std::str::FromStr;

/// Represents the address family in the `interfaces(5)` file.
///
/// The `Family` enum constrains the `family` field to allowed values, ensuring
/// that only valid address families are used.
///
/// # Variants
///
/// - `Inet`: Represents the `inet` family (IPv4).
/// - `Inet6`: Represents the `inet6` family (IPv6).
/// - `IpX`: Represents the `ipx` family.
/// - `Can`: Represents the `can` family.
///
/// # Examples
///
/// Parsing a `Family` from a string:
///
/// ```rust
/// use interface_rs::interface::Family;
/// use std::str::FromStr;
///
/// let family = Family::from_str("inet").unwrap();
/// assert_eq!(family, Family::Inet);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum Family {
    /// The `inet` address family (IPv4).
    Inet,
    /// The `inet6` address family (IPv6).
    Inet6,
    /// The `ipx` address family.
    IpX,
    /// The `can` address family.
    Can,
}

impl fmt::Display for Family {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let family_str = match self {
            Family::Inet => "inet",
            Family::Inet6 => "inet6",
            Family::IpX => "ipx",
            Family::Can => "can",
        };
        write!(f, "{}", family_str)
    }
}

impl FromStr for Family {
    type Err = FamilyParseError;

    /// Parses a `Family` from a string slice.
    ///
    /// # Errors
    ///
    /// Returns a `FamilyParseError` if the input string does not match any known family.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "inet" => Ok(Family::Inet),
            "inet6" => Ok(Family::Inet6),
            "ipx" => Ok(Family::IpX),
            "can" => Ok(Family::Can),
            _ => Err(FamilyParseError(s.to_string())),
        }
    }
}

/// An error that occurs when parsing a `Family` from a string.
///
/// This error is returned when the input string does not correspond to any
/// known address family.
#[derive(Debug, Clone)]
pub struct FamilyParseError(pub String);

impl fmt::Display for FamilyParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Invalid family: {}", self.0)
    }
}

impl Error for FamilyParseError {}