session_rust/
vertex.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3use uuid::Uuid;
4
5/// A graph vertex with a unique identifier and attribute string.
6#[derive(Debug, Clone, Serialize, Deserialize)]
7#[serde(tag = "type", rename = "Vertex")]
8pub struct Vertex {
9    /// The unique identifier of the vertex.
10    pub guid: String,
11    /// The name of the vertex.
12    pub name: String,
13    /// Vertex attribute data as string.
14    pub attribute: String,
15    /// Integer index for the vertex. Set internally by Graph.
16    pub index: i32,
17}
18
19impl Default for Vertex {
20    fn default() -> Self {
21        Self {
22            name: "my_vertex".to_string(),
23            guid: Uuid::new_v4().to_string(),
24            attribute: String::new(),
25            index: -1,
26        }
27    }
28}
29
30impl fmt::Display for Vertex {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        write!(
33            f,
34            "Vertex({}, {}, attr={}, index={})",
35            self.name, self.guid, self.attribute, self.index
36        )
37    }
38}
39
40impl Vertex {
41    /// Initialize a new Vertex.
42    pub fn new(name: Option<String>, attribute: Option<String>) -> Self {
43        Self {
44            name: name.unwrap_or_default(),
45            attribute: attribute.unwrap_or_default(),
46            ..Default::default()
47        }
48    }
49
50    ///////////////////////////////////////////////////////////////////////////////////////////
51    // JSON
52    ///////////////////////////////////////////////////////////////////////////////////////////
53
54    /// Convert the Vertex to a JSON-serializable string.
55    pub fn jsondump(&self) -> Result<String, Box<dyn std::error::Error>> {
56        Ok(serde_json::to_string_pretty(self)?)
57    }
58
59    /// Create Vertex from JSON string data.
60    pub fn jsonload(json_data: &str) -> Result<Self, Box<dyn std::error::Error>> {
61        Ok(serde_json::from_str(json_data)?)
62    }
63}
64
65#[cfg(test)]
66#[path = "vertex_test.rs"]
67mod vertex_test;