Skip to main content

weavatrix_graph/model/
element.rs

1use super::{NodeId, Provenance, SourceSpan};
2use crate::String;
3use crate::{AttributeValue, EdgeKind, NodeKind, Result};
4use alloc::collections::BTreeMap;
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8pub struct Node {
9    pub id: NodeId,
10    pub label: String,
11    pub kind: NodeKind,
12    #[serde(skip_serializing_if = "Option::is_none")]
13    pub language: Option<String>,
14    #[serde(skip_serializing_if = "Option::is_none")]
15    pub span: Option<SourceSpan>,
16    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
17    pub attributes: BTreeMap<String, AttributeValue>,
18}
19
20impl Node {
21    /// Creates a graph node.
22    ///
23    /// # Errors
24    ///
25    /// Returns an error when the node identifier is empty.
26    pub fn new(id: impl Into<String>, label: impl Into<String>, kind: NodeKind) -> Result<Self> {
27        Ok(Self {
28            id: NodeId::new(id)?,
29            label: label.into(),
30            kind,
31            language: None,
32            span: None,
33            attributes: BTreeMap::new(),
34        })
35    }
36
37    #[must_use]
38    pub fn with_language(mut self, language: impl Into<String>) -> Self {
39        self.language = Some(language.into());
40        self
41    }
42
43    #[must_use]
44    pub fn with_span(mut self, span: SourceSpan) -> Self {
45        self.span = Some(span);
46        self
47    }
48
49    #[must_use]
50    pub fn with_attribute(
51        mut self,
52        key: impl Into<String>,
53        value: impl Into<AttributeValue>,
54    ) -> Self {
55        self.attributes.insert(key.into(), value.into());
56        self
57    }
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
61pub struct Edge {
62    pub source: NodeId,
63    pub target: NodeId,
64    pub kind: EdgeKind,
65    pub provenance: Provenance,
66    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
67    pub attributes: BTreeMap<String, AttributeValue>,
68}
69
70impl Edge {
71    #[must_use]
72    pub fn new(source: NodeId, target: NodeId, kind: EdgeKind, provenance: Provenance) -> Self {
73        Self {
74            source,
75            target,
76            kind,
77            provenance,
78            attributes: BTreeMap::new(),
79        }
80    }
81
82    #[must_use]
83    pub fn with_attribute(
84        mut self,
85        key: impl Into<String>,
86        value: impl Into<AttributeValue>,
87    ) -> Self {
88        self.attributes.insert(key.into(), value.into());
89        self
90    }
91}