Skip to main content

nodedb_types/
graph.rs

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