Skip to main content

neco_nodegraph/
node.rs

1use alloc::vec::Vec;
2
3use crate::error::GraphError;
4use crate::id::{NodeId, PortId};
5use crate::port::Port;
6
7/// A graph node with payload and typed ports.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Node<N> {
10    id: NodeId,
11    payload: N,
12    ports: Vec<Port>,
13}
14
15impl<N> Node<N> {
16    /// Creates a node with the provided identifier, payload, and ports.
17    pub fn new(id: NodeId, payload: N, ports: Vec<Port>) -> Self {
18        Self { id, payload, ports }
19    }
20
21    /// Returns the node identifier.
22    pub const fn id(&self) -> NodeId {
23        self.id
24    }
25
26    /// Returns the stored payload.
27    pub fn payload(&self) -> &N {
28        &self.payload
29    }
30
31    /// Returns mutable access to the stored payload.
32    pub fn payload_mut(&mut self) -> &mut N {
33        &mut self.payload
34    }
35
36    /// Returns the declared ports.
37    pub fn ports(&self) -> &[Port] {
38        self.ports.as_slice()
39    }
40
41    /// Adds a port when its identifier is not already present.
42    pub fn add_port(&mut self, port: Port) -> Result<(), GraphError> {
43        if self.ports.iter().any(|existing| existing.id() == port.id()) {
44            return Err(GraphError::DuplicatePort(port.id().clone()));
45        }
46        self.ports.push(port);
47        Ok(())
48    }
49
50    /// Returns the port with the given identifier.
51    pub fn port(&self, port_id: &PortId) -> Option<&Port> {
52        self.ports.iter().find(|port| port.id() == port_id)
53    }
54}