session_rust/
edge.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3use uuid::Uuid;
4
5impl fmt::Display for Edge {
6    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7        write!(
8            f,
9            "Edge({}, {}, {} -> {}, attr={}, index={})",
10            self.name, self.guid, self.v0, self.v1, self.attribute, self.index
11        )
12    }
13}
14
15/// A graph edge with a unique identifier and attribute string.
16#[derive(Debug, Clone, Serialize, Deserialize)]
17#[serde(tag = "type", rename = "Edge")]
18pub struct Edge {
19    /// The unique identifier of the edge.
20    pub guid: String,
21    /// The name of the edge.
22    pub name: String,
23    /// The first vertex of the edge.
24    pub v0: String,
25    /// The second vertex of the edge.
26    pub v1: String,
27    /// Edge attribute data as string.
28    pub attribute: String,
29    /// Integer index for the edge.
30    pub index: i32,
31}
32
33impl Default for Edge {
34    fn default() -> Self {
35        Self {
36            name: "my_edge".to_string(),
37            guid: Uuid::new_v4().to_string(),
38            v0: String::new(),
39            v1: String::new(),
40            attribute: String::new(),
41            index: -1,
42        }
43    }
44}
45
46impl Edge {
47    /// Initialize a new Edge.
48    pub fn new(
49        name: Option<String>,
50        v0: Option<String>,
51        v1: Option<String>,
52        attribute: Option<String>,
53    ) -> Self {
54        Self {
55            name: name.unwrap_or_default(),
56            v0: v0.unwrap_or_default(),
57            v1: v1.unwrap_or_default(),
58            attribute: attribute.unwrap_or_default(),
59            ..Default::default()
60        }
61    }
62
63    ///////////////////////////////////////////////////////////////////////////////////////////
64    // JSON
65    ///////////////////////////////////////////////////////////////////////////////////////////
66
67    /// Convert the Edge to a JSON-serializable string.
68    pub fn jsondump(&self) -> Result<String, Box<dyn std::error::Error>> {
69        Ok(serde_json::to_string_pretty(self)?)
70    }
71
72    /// Create Edge from JSON string data.
73    pub fn jsonload(json_data: &str) -> Result<Self, Box<dyn std::error::Error>> {
74        Ok(serde_json::from_str(json_data)?)
75    }
76
77    /// Get the edge vertices as a tuple.
78    pub fn vertices(&self) -> (String, String) {
79        (self.v0.clone(), self.v1.clone())
80    }
81
82    /// Check if this edge connects to a given vertex.
83    pub fn connects(&self, vertex_id: &str) -> bool {
84        self.v0 == vertex_id || self.v1 == vertex_id
85    }
86
87    /// Get the other vertex ID connected by this edge.
88    pub fn other_vertex(&self, vertex_id: &str) -> String {
89        if self.v0 == vertex_id {
90            self.v1.clone()
91        } else {
92            self.v0.clone()
93        }
94    }
95}
96
97#[cfg(test)]
98#[path = "edge_test.rs"]
99mod edge_test;