1use serde::{Deserialize, Serialize};
6
7#[derive(
9 Debug,
10 Clone,
11 Copy,
12 PartialEq,
13 Eq,
14 Hash,
15 Serialize,
16 Deserialize,
17 zerompk::ToMessagePack,
18 zerompk::FromMessagePack,
19)]
20#[msgpack(c_enum)]
21pub enum Direction {
22 Out,
24 In,
26 Both,
28}
29
30impl Direction {
31 pub fn as_str(&self) -> &'static str {
32 match self {
33 Self::Out => "out",
34 Self::In => "in",
35 Self::Both => "both",
36 }
37 }
38}
39
40impl std::fmt::Display for Direction {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 f.write_str(self.as_str())
43 }
44}
45
46impl std::str::FromStr for Direction {
47 type Err = String;
48 fn from_str(s: &str) -> Result<Self, Self::Err> {
49 match s.to_lowercase().as_str() {
50 "out" | "outgoing" => Ok(Self::Out),
51 "in" | "incoming" => Ok(Self::In),
52 "both" | "any" => Ok(Self::Both),
53 other => Err(format!("unknown direction: '{other}'")),
54 }
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 #[test]
63 fn direction_roundtrip() {
64 for dir in [Direction::Out, Direction::In, Direction::Both] {
65 let s = dir.as_str();
66 let parsed: Direction = s.parse().unwrap();
67 assert_eq!(dir, parsed);
68 }
69 }
70
71 #[test]
72 fn direction_display() {
73 assert_eq!(Direction::Out.to_string(), "out");
74 }
75}