Skip to content

Commit

Permalink
dag/lib: Add this new invention: Documentation
Browse files Browse the repository at this point in the history
Signed-off-by: Ikey Doherty <ikey@serpentos.com>
  • Loading branch information
ikeycode committed Oct 14, 2023
1 parent abe4b78 commit 88b97e2
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions dag/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@ use self::subgraph::subgraph;

mod subgraph;

/// NodeIndex as employed in moss-rs usage
pub type NodeIndex = petgraph::prelude::NodeIndex<u32>;

/// Simplistic encapsulation of petgraph APIs to provide
/// suitable mechanisms to empower transaction code
#[derive(Debug, Clone)]
pub struct Dag<N>(DiGraph<N, (), u32>);

Expand All @@ -26,6 +29,7 @@ impl<N> Dag<N>
where
N: Clone + PartialEq,
{
/// Construct a new Dag
pub fn new() -> Self {
Self::default()
}
Expand All @@ -40,10 +44,12 @@ where
}
}

/// Returns true if the node exists
pub fn node_exists(&self, node: &N) -> bool {
self.get_index(node).is_some()
}

/// Remove node
pub fn remove_node(&mut self, node: &N) -> Option<N> {
if let Some(index) = self.get_index(node) {
self.0.remove_node(index)
Expand All @@ -52,6 +58,7 @@ where
}
}

/// Add an edge from a to b
pub fn add_edge(&mut self, a: NodeIndex, b: NodeIndex) -> bool {
let a_node = &self.0[a];

Expand All @@ -75,28 +82,33 @@ where
self.0.node_indices().map(|i| &self.0[i])
}

/// Perform a depth-first search, given the start index
pub fn dfs(&self, start: NodeIndex) -> impl Iterator<Item = &'_ N> {
let dfs = Dfs::new(&self.0, start);

dfs.iter(&self.0).map(|i| &self.0[i])
}

/// Perform a toplogical sort
pub fn topo(&self) -> impl Iterator<Item = &'_ N> {
let topo = Topo::new(&self.0);

topo.iter(&self.0).map(|i| &self.0[i])
}

/// Transpose the graph, returning the clone
pub fn transpose(&self) -> Self {
let mut transposed = self.0.clone();
transposed.reverse();
Self(transposed)
}

/// Split the graph at the given start node(s) - returning a new graph
pub fn subgraph(&self, starting_nodes: &[N]) -> Self {
Self(subgraph(&self.0, starting_nodes))
}

/// Return the index for node of type N
pub fn get_index(&self, node: &N) -> Option<NodeIndex> {
self.0.node_indices().find(|i| self.0[*i] == *node)
}
Expand Down

0 comments on commit 88b97e2

Please sign in to comment.