fast_graph/node.rs
1//! # [Node] is a struct representing a node in the graph,
2//! --- which has a generic data field and a list of [EdgeID]s.
3//!
4//! A [NodeID] is a key to the node in the slotmap.
5//!
6//! # Why is there no "NodeTrait"?
7//!
8//! The [Node] struct is very simple and doesn't need a trait.
9//! If you want to add more functionality or data to the Node you can probably just add it to the data field, or add a node as a field to your custom type.
10
11use super::*;
12use slotmap::{new_key_type, KeyData};
13
14new_key_type! {
15 /// A key to the node in the slotmap.
16 pub struct NodeID;
17}
18
19impl NodeID {
20 pub fn to_u64(&self) -> u64 {
21 self.0.as_ffi()
22 }
23 pub fn from_u64(id: u64) -> Self {
24 NodeID::from(KeyData::from_ffi(id))
25 }
26}
27
28/* -------------------------------------------------------------------------- */
29/* Node */
30/* -------------------------------------------------------------------------- */
31
32/// # A struct representing a node/vertex in the graph.
33/// Has a generic data field and a list of [EdgeID]s.
34///
35/// A [NodeID] is a key to the node in the slotmap.
36///
37/// ## Why is there no "NodeTrait"?
38///
39/// The [Node] struct is very simple and doesn't need a trait.
40/// If you want to add more functionality or data to the Node you can probably just add it to the data field, or add a node as a field to your custom type.
41#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42#[cfg_attr(feature = "specta", derive(specta::Type))]
43pub struct Node<T> {
44 pub id: NodeID,
45 pub data: T,
46 pub connections: Vec<EdgeID>,
47}
48
49/// Implements PartialEQ for Node<T> so only the ID is used for comparison.
50impl<T> PartialEq for Node<T> {
51 fn eq(&self, other: &Self) -> bool {
52 self.id == other.id
53 }
54}
55
56/// Implements Hash for Node<T> so only the ID is used for hashing.
57impl<T: std::hash::Hash> std::hash::Hash for Node<T> {
58 fn hash<H: std::hash::Hasher>(&self, ra_expand_state: &mut H) {
59 self.id.hash(ra_expand_state);
60 }
61}
62
63/* ---------------------------------- Debug --------------------------------- */
64
65impl<T: fmt::Debug> fmt::Debug for Node<T> {
66 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
67 write!(
68 f,
69 "Node {{ id: {:#?}, data: {:#?}, connections: {:#?} }}",
70 self.id, self.data, self.connections
71 )
72 }
73}
74
75impl<T> Node<T> {
76 pub fn new(id: NodeID, data: T) -> Node<T> {
77 Node {
78 id,
79 data,
80 connections: Vec::new(),
81 }
82 }
83
84 pub fn add_connection(&mut self, edge: EdgeID) {
85 self.connections.push(edge);
86 }
87}