ratio-graph 0.23.3

Ratio's graph manipulation library.
Documentation
//! # Graph module
//!
//! ## License
//!
//! This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
//! If a copy of the MPL was not distributed with this file,
//! You can obtain one at <https://mozilla.org/MPL/2.0/>.
//!
//! **Code examples both in the docstrings and rendered documentation are free to use.**

use snafu::{ResultExt, Snafu};

pub use crate::{
    Edge, EdgeStore, EdgeStoreData, HasEdgeStore, HasNodeStore, Meta, Metadata, Node, NodeStore,
    NodeStoreData,
};

/// Graph error.
#[derive(Clone, Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
    /// NodeStore error.
    NodeStore { source: crate::node::NodeStoreError },
    /// EdgeStore error.
    EdgeStore { source: crate::edge::EdgeStoreError },
}

/// A graph containing nodes and edges.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(default)
)]
pub struct Graph {
    /// Instance metadata.
    pub metadata: Metadata,
    /// Node store.
    pub nodes: NodeStoreData,
    /// Edge store.
    pub edges: EdgeStoreData,
}

impl HasNodeStore for Graph {
    fn node_store(&self) -> &NodeStoreData {
        &self.nodes
    }
    fn node_store_mut(&mut self) -> &mut NodeStoreData {
        &mut self.nodes
    }
}
impl NodeStore for Graph {}
impl HasEdgeStore for Graph {
    fn edge_store(&self) -> &EdgeStoreData {
        &self.edges
    }
    fn edge_store_mut(&mut self) -> &mut EdgeStoreData {
        &mut self.edges
    }
}
impl EdgeStore for Graph {}

impl Graph {
    pub fn new(
        metadata: Option<Metadata>,
        nodes: Vec<Node>,
        edges: Vec<Edge>,
    ) -> Result<Self, Error> {
        let mut node_store = NodeStoreData::default();
        node_store
            .extend_nodes(nodes, true)
            .with_context(|_| NodeStoreSnafu)?;
        let mut edge_store = EdgeStoreData::default();
        edge_store
            .extend_edges(edges, true, Some(&node_store))
            .with_context(|_| EdgeStoreSnafu)?;
        let graph = Self {
            metadata: metadata.unwrap_or_default(),
            nodes: node_store,
            edges: edge_store,
        };
        Ok(graph)
    }
}

impl Meta for Graph {
    fn get_meta(&self) -> &Metadata {
        &self.metadata
    }
}