Skip to main content

vecgraph_core/
node.rs

1use crate::VecGraphError;
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
5pub struct NodeId(pub String);
6
7impl NodeId {
8    pub fn new(id: impl Into<String>) -> Self {
9        Self(id.into())
10    }
11
12    pub fn try_new(id: impl Into<String>) -> Result<Self, VecGraphError> {
13        let s: String = id.into();
14        if s.is_empty() {
15            return Err(VecGraphError::InvalidId("NodeId cannot be empty".into()));
16        }
17        if s.contains(':') || s.chars().any(char::is_whitespace) {
18            return Err(VecGraphError::InvalidId(format!(
19                "NodeId may not contain ':' or whitespace: {:?}",
20                s
21            )));
22        }
23        Ok(Self(s))
24    }
25
26    pub fn as_str(&self) -> &str {
27        &self.0
28    }
29}
30
31impl std::fmt::Display for NodeId {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.write_str(&self.0)
34    }
35}
36
37impl<T: Into<String>> From<T> for NodeId {
38    fn from(val: T) -> Self {
39        Self(val.into())
40    }
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct Node {
45    pub id: NodeId,
46    pub kind: String,
47    pub namespace: Option<String>,
48    pub name: String,
49    pub payload: serde_json::Value,
50}
51
52impl Node {
53    pub fn new(
54        id: impl Into<NodeId>,
55        kind: impl Into<String>,
56        name: impl Into<String>,
57        payload: serde_json::Value,
58    ) -> Self {
59        Self {
60            id: id.into(),
61            kind: kind.into(),
62            namespace: None,
63            name: name.into(),
64            payload,
65        }
66    }
67
68    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
69        self.namespace = Some(namespace.into());
70        self
71    }
72
73    pub fn payload_as<T: serde::de::DeserializeOwned>(&self) -> Option<T> {
74        serde_json::from_value(self.payload.clone()).ok()
75    }
76}
77
78#[derive(Debug, Clone, Serialize, Deserialize)]
79pub struct NodeWithVector {
80    pub node: Node,
81    pub vector: Vec<f32>,
82}
83
84impl NodeWithVector {
85    pub fn new(node: Node, vector: Vec<f32>) -> Self {
86        Self { node, vector }
87    }
88}