acorn_lib/schema/
graph.rs

1//! ## Graph Utilities
2//!
3//! This module provides functions for working with graph data structures.
4//!
5//! <div class="warning">Primary use is to model organizational data as a graph.</div>
6use petgraph::stable_graph::NodeIndex;
7use petgraph::visit::EdgeRef;
8use petgraph::{graph::Graph, Direction};
9
10type _Graph = Graph<String, u8>;
11/// Find a node by label.
12///
13/// # Arguments
14///
15/// * `graph` - The graph to search.
16/// * `label` - The label to search for.
17///
18/// # Return
19///
20/// The node index with the given `label`, or `None` if not found.
21pub fn node_from_label(graph: &_Graph, label: &str) -> Option<NodeIndex> {
22    match graph.node_indices().find(|n| graph[*n] == label) {
23        | Some(node) => Some(node),
24        | None => None,
25    }
26}
27/// Get the name of a node in the graph.
28///
29/// # Arguments
30///
31/// * `graph` - The graph containing the node.
32/// * `node` - The node whose name to retrieve.
33///
34/// # Return
35///
36/// The name associated with the node, or `None` if not found.
37pub fn node_name(graph: &_Graph, node: NodeIndex) -> Option<String> {
38    match graph.node_weight(node) {
39        | Some(value) => Some(value.to_string()),
40        | None => None,
41    }
42}
43/// Find the parent of a node in the graph.
44///
45/// # Arguments
46///
47/// * `graph` - The graph containing the node.
48/// * `node` - The node whose parent to retrieve.
49///
50/// # Return
51///
52/// The parent of the node, or `None` if not found.
53pub fn node_parent(graph: &_Graph, node: NodeIndex) -> Option<NodeIndex> {
54    match graph.edges_directed(node, Direction::Incoming).clone().next() {
55        | Some(edge) => Some(edge.source()),
56        | None => None,
57    }
58}