Skip to main content

async_snmp/
version.rs

1//! SNMP version enumeration.
2
3/// SNMP protocol version.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5#[non_exhaustive]
6#[derive(Default)]
7pub enum Version {
8    /// SNMPv1 (RFC 1157)
9    V1,
10    /// SNMPv2c (RFC 1901)
11    #[default]
12    V2c,
13    /// SNMPv3 (RFC 3411-3418)
14    V3,
15}
16
17impl Version {
18    /// Get the BER-encoded version number.
19    ///
20    /// # Examples
21    ///
22    /// ```
23    /// use async_snmp::Version;
24    ///
25    /// assert_eq!(Version::V1.as_i32(), 0);
26    /// assert_eq!(Version::V2c.as_i32(), 1);
27    /// assert_eq!(Version::V3.as_i32(), 3);
28    /// ```
29    pub const fn as_i32(self) -> i32 {
30        match self {
31            Version::V1 => 0,
32            Version::V2c => 1,
33            Version::V3 => 3,
34        }
35    }
36
37    /// Create from BER-encoded version number.
38    ///
39    /// # Examples
40    ///
41    /// ```
42    /// use async_snmp::Version;
43    ///
44    /// assert_eq!(Version::from_i32(0), Some(Version::V1));
45    /// assert_eq!(Version::from_i32(1), Some(Version::V2c));
46    /// assert_eq!(Version::from_i32(3), Some(Version::V3));
47    /// assert_eq!(Version::from_i32(2), None); // Invalid version
48    /// ```
49    pub const fn from_i32(value: i32) -> Option<Self> {
50        match value {
51            0 => Some(Version::V1),
52            1 => Some(Version::V2c),
53            3 => Some(Version::V3),
54            _ => None,
55        }
56    }
57}
58
59impl TryFrom<i32> for Version {
60    type Error = i32;
61
62    fn try_from(value: i32) -> std::result::Result<Self, i32> {
63        Self::from_i32(value).ok_or(value)
64    }
65}
66
67impl std::fmt::Display for Version {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        match self {
70            Version::V1 => write!(f, "SNMPv1"),
71            Version::V2c => write!(f, "SNMPv2c"),
72            Version::V3 => write!(f, "SNMPv3"),
73        }
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn test_version_try_from() {
83        assert_eq!(Version::try_from(0), Ok(Version::V1));
84        assert_eq!(Version::try_from(1), Ok(Version::V2c));
85        assert_eq!(Version::try_from(3), Ok(Version::V3));
86        assert_eq!(Version::try_from(2), Err(2));
87        assert_eq!(Version::try_from(-1), Err(-1));
88    }
89}