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#[derive(Debug, Clone, Serialize, Deserialize)]
17#[serde(tag = "type", rename = "Edge")]
18pub struct Edge {
19 pub guid: String,
21 pub name: String,
23 pub v0: String,
25 pub v1: String,
27 pub attribute: String,
29 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 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 pub fn jsondump(&self) -> Result<String, Box<dyn std::error::Error>> {
69 Ok(serde_json::to_string_pretty(self)?)
70 }
71
72 pub fn jsonload(json_data: &str) -> Result<Self, Box<dyn std::error::Error>> {
74 Ok(serde_json::from_str(json_data)?)
75 }
76
77 pub fn vertices(&self) -> (String, String) {
79 (self.v0.clone(), self.v1.clone())
80 }
81
82 pub fn connects(&self, vertex_id: &str) -> bool {
84 self.v0 == vertex_id || self.v1 == vertex_id
85 }
86
87 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;