Skip to content

Commit 7362852

Browse files
committed
impl FromStr for NeighbourState
1 parent 6dd74c9 commit 7362852

1 file changed

Lines changed: 72 additions & 0 deletions

File tree

src/neighbour/state.rs

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// SPDX-License-Identifier: MIT
22

3+
use netlink_packet_core::DecodeError;
4+
35
const NUD_INCOMPLETE: u16 = 0x01;
46
const NUD_REACHABLE: u16 = 0x02;
57
const NUD_STALE: u16 = 0x04;
@@ -76,3 +78,73 @@ impl std::fmt::Display for NeighbourState {
7678
}
7779
}
7880
}
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

Comments
 (0)