|
1 | 1 | // SPDX-License-Identifier: MIT |
2 | 2 |
|
| 3 | +use netlink_packet_core::DecodeError; |
| 4 | + |
3 | 5 | const NUD_INCOMPLETE: u16 = 0x01; |
4 | 6 | const NUD_REACHABLE: u16 = 0x02; |
5 | 7 | const NUD_STALE: u16 = 0x04; |
@@ -76,3 +78,73 @@ impl std::fmt::Display for NeighbourState { |
76 | 78 | } |
77 | 79 | } |
78 | 80 | } |
| 81 | + |
| 82 | +impl std::str::FromStr for NeighbourState { |
| 83 | + type Err = DecodeError; |
| 84 | + |
| 85 | + fn from_str(state: &str) -> Result<Self, Self::Err> { |
| 86 | + let state = match state { |
| 87 | + "incomplete" => Self::Incomplete, |
| 88 | + "reachable" => Self::Reachable, |
| 89 | + "stale" => Self::Stale, |
| 90 | + "delay" => Self::Delay, |
| 91 | + "probe" => Self::Probe, |
| 92 | + "failed" => Self::Failed, |
| 93 | + "noarp" => Self::Noarp, |
| 94 | + "permanent" => Self::Permanent, |
| 95 | + "none" => Self::None, |
| 96 | + _ => return Err(format!("Invalid state string '{state}'").into()), |
| 97 | + }; |
| 98 | + |
| 99 | + Ok(state) |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +#[cfg(test)] |
| 104 | +mod tests { |
| 105 | + use std::str::FromStr; |
| 106 | + |
| 107 | + use super::NeighbourState; |
| 108 | + |
| 109 | + #[test] |
| 110 | + fn test_neighbour_state_decoding() { |
| 111 | + assert!(matches!( |
| 112 | + NeighbourState::from_str("incomplete"), |
| 113 | + Ok(NeighbourState::Incomplete) |
| 114 | + )); |
| 115 | + assert!(matches!( |
| 116 | + NeighbourState::from_str("reachable"), |
| 117 | + Ok(NeighbourState::Reachable) |
| 118 | + )); |
| 119 | + assert!(matches!( |
| 120 | + NeighbourState::from_str("stale"), |
| 121 | + Ok(NeighbourState::Stale) |
| 122 | + )); |
| 123 | + assert!(matches!( |
| 124 | + NeighbourState::from_str("delay"), |
| 125 | + Ok(NeighbourState::Delay) |
| 126 | + )); |
| 127 | + assert!(matches!( |
| 128 | + NeighbourState::from_str("probe"), |
| 129 | + Ok(NeighbourState::Probe) |
| 130 | + )); |
| 131 | + assert!(matches!( |
| 132 | + NeighbourState::from_str("failed"), |
| 133 | + Ok(NeighbourState::Failed) |
| 134 | + )); |
| 135 | + assert!(matches!( |
| 136 | + NeighbourState::from_str("noarp"), |
| 137 | + Ok(NeighbourState::Noarp) |
| 138 | + )); |
| 139 | + assert!(matches!( |
| 140 | + NeighbourState::from_str("permanent"), |
| 141 | + Ok(NeighbourState::Permanent) |
| 142 | + )); |
| 143 | + assert!(matches!( |
| 144 | + NeighbourState::from_str("none"), |
| 145 | + Ok(NeighbourState::None) |
| 146 | + )); |
| 147 | + assert!(matches!(NeighbourState::from_str("None"), Err(..))); |
| 148 | + assert!(matches!(NeighbourState::from_str("not a nud"), Err(..))); |
| 149 | + } |
| 150 | +} |
0 commit comments