dagis 0.1.0

Directed acyclic graph checker
Documentation
use crate::DiGraph;

/// Directed graph with vertices carrying a payload of any clonable type.
#[derive(Debug, Default, Clone)]
pub struct TypedDiGraph<T: Clone> {
    graph: DiGraph,
    payloads: Vec<T>,
}

impl<T: Clone> TypedDiGraph<T> {
    /// Creates a vertex with payload.
    pub fn vertex(&mut self, payload: T) -> usize {
        let id = self.graph.vertex();
        self.payloads.push(payload);
        id
    }

    /// Creates a directed edge between vertices.
    pub fn edge(&mut self, source: usize, sink: usize) {
        self.graph.edge(source, sink);
    }

    /// Returns `true` when a graph is acyclic.
    #[must_use]
    pub fn acyclic(&self) -> bool {
        self.graph.acyclic()
    }

    /// Returns the first found cycle.
    #[must_use]
    pub fn cycle(&self) -> Vec<T> {
        self.graph
            .cycle()
            .into_iter()
            .map(|i| self.payloads[i].clone())
            .collect()
    }

    /// Returns topologically sorted payloads of vertices.
    #[must_use]
    pub fn sort(&self) -> Vec<T> {
        self.graph
            .sort()
            .into_iter()
            .map(|i| self.payloads[i].clone())
            .collect()
    }
}