ratio_graph/
graph.rs

1//! # Graph module
2//!
3//! ## License
4//!
5//! This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
6//! If a copy of the MPL was not distributed with this file,
7//! You can obtain one at <https://mozilla.org/MPL/2.0/>.
8//!
9//! **Code examples both in the docstrings and rendered documentation are free to use.**
10
11use snafu::{ResultExt, Snafu};
12
13pub use crate::{
14    Edge, EdgeStore, EdgeStoreData, HasEdgeStore, HasNodeStore, Meta, Metadata, Node, NodeStore,
15    NodeStoreData,
16};
17
18/// Graph error.
19#[derive(Clone, Debug, Snafu)]
20#[snafu(visibility(pub(crate)))]
21pub enum Error {
22    /// NodeStore error.
23    NodeStore { source: crate::node::NodeStoreError },
24    /// EdgeStore error.
25    EdgeStore { source: crate::edge::EdgeStoreError },
26}
27
28/// A graph containing nodes and edges.
29#[derive(Clone, Debug, Default, PartialEq)]
30#[cfg_attr(
31    feature = "serde",
32    derive(serde::Serialize, serde::Deserialize),
33    serde(default)
34)]
35pub struct Graph {
36    /// Instance metadata.
37    pub metadata: Metadata,
38    /// Node store.
39    pub nodes: NodeStoreData,
40    /// Edge store.
41    pub edges: EdgeStoreData,
42}
43
44impl HasNodeStore for Graph {
45    fn node_store(&self) -> &NodeStoreData {
46        &self.nodes
47    }
48    fn node_store_mut(&mut self) -> &mut NodeStoreData {
49        &mut self.nodes
50    }
51}
52impl NodeStore for Graph {}
53impl HasEdgeStore for Graph {
54    fn edge_store(&self) -> &EdgeStoreData {
55        &self.edges
56    }
57    fn edge_store_mut(&mut self) -> &mut EdgeStoreData {
58        &mut self.edges
59    }
60}
61impl EdgeStore for Graph {}
62
63impl Graph {
64    pub fn new(
65        metadata: Option<Metadata>,
66        nodes: Vec<Node>,
67        edges: Vec<Edge>,
68    ) -> Result<Self, Error> {
69        let mut node_store = NodeStoreData::default();
70        node_store
71            .extend_nodes(nodes, true)
72            .with_context(|_| NodeStoreSnafu)?;
73        let mut edge_store = EdgeStoreData::default();
74        edge_store
75            .extend_edges(edges, true, Some(&node_store))
76            .with_context(|_| EdgeStoreSnafu)?;
77        let graph = Self {
78            metadata: metadata.unwrap_or_default(),
79            nodes: node_store,
80            edges: edge_store,
81        };
82        Ok(graph)
83    }
84}
85
86impl Meta for Graph {
87    fn get_meta(&self) -> &Metadata {
88        &self.metadata
89    }
90}