grapes 0.3.0

Persistent graph data structures: Tree, Graph, Arena & more
Documentation
//! Mutable references to nodes

use crate::graph::{EdgesFrom, EdgesTo, Graph, Node, NodeId};

/// Mutable reference to a node in a [Graph]
///
/// The library guarantees that this references a valid node
#[derive(Debug)]
pub struct NodeMut<'a, NodeData: Clone, EdgeData: Clone> {
    pub(crate) graph: &'a mut Graph<NodeData, EdgeData>,
    pub(crate) index: NodeId,
}

impl<'a, NodeData: Clone, EdgeData: Clone> NodeMut<'a, NodeData, EdgeData> {
    #[must_use]
    pub(crate) fn new(graph: &'a mut Graph<NodeData, EdgeData>, index: NodeId) -> Self {
        Self { graph, index }
    }
    /// Get the node this [NodeMut] points to
    ///
    /// (internal convenience method)
    #[must_use]
    fn node(&self) -> &Node<NodeData> {
        self.graph
            .nodes
            .get(self.index.0)
            .expect("invariant violation: NodeMut points to invalid node")
    }

    /// Get a mutable reference to the node this [NodeMut] points to
    ///
    /// (internal convenience method)
    #[must_use]
    fn node_mut(&mut self) -> &mut Node<NodeData> {
        self.graph
            .nodes
            .get_mut(self.index.0)
            .expect("invariant violation: NodeMut points to invalid node")
    }

    /// The data associated with the node
    ///
    /// (a.k.a. the node weight)
    #[must_use]
    pub fn data(&self) -> &NodeData {
        &self.node().data
    }

    /// A mutable reference to the data associated with the node
    ///
    /// (a.k.a. the node weight)
    #[must_use]
    pub fn data_mut(&mut self) -> &mut NodeData {
        &mut self.node_mut().data
    }

    /// The node's identifier
    ///
    /// You can use this to later reference the node in the graph (if it still exists)
    #[must_use]
    pub fn id(&self) -> NodeId {
        self.index
    }

    /// Iterate over edges leaving this node
    ///
    /// Order is unspecified.
    pub fn iter_edges_from(&self) -> EdgesFrom<NodeData, EdgeData> {
        EdgesFrom::new(self.graph, self.node().first_edge_from)
    }

    /// Iterate over edges entering this node
    ///
    /// Order is unspecified.
    pub fn iter_edges_to(&self) -> EdgesTo<NodeData, EdgeData> {
        EdgesTo::new(self.graph, self.node().first_edge_to)
    }

    /// Remove this node from the graph, along with all edges adjacent to it
    ///
    /// Returns the associated data of the removed node
    #[allow(clippy::must_use_candidate)]
    pub fn remove(self) -> NodeData {
        let removed = self
            .graph
            .nodes
            .remove(self.index.0)
            .expect("invariant violation: NodeMut points to invalid node");

        self.graph.remove_all_edges_connecting(self.index, &removed);

        removed.data
    }
}