dagis 0.2.0

A fast directed acyclic graph (DAG) checker
Documentation
/// Vertex identifier.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VertexId(usize);

/// A graph vertex with associated label.
pub trait LabeledVertex<L> {
    /// Adds a vertex to the graph with the given label.
    ///
    /// Returns the identifier of the newly added vertex.
    fn add_vertex(&mut self, label: L) -> VertexId;
}

/// Directed graph.
#[derive(Debug)]
pub struct DiGraph<L = ()> {
    successors: Vec<Vec<usize>>,
    predecessors: Vec<Vec<usize>>,
    labels: Vec<L>,
}

impl<L> Default for DiGraph<L> {
    fn default() -> Self {
        Self::new()
    }
}

impl<L> LabeledVertex<L> for DiGraph<L> {
    /// Adds a new vertex with label.
    fn add_vertex(&mut self, label: L) -> VertexId {
        self.successors.push(Vec::new());
        self.predecessors.push(Vec::new());
        self.labels.push(label);
        VertexId(self.predecessors.len() - 1)
    }
}

impl DiGraph<()> {
    /// Adds a new vertex.
    pub fn add_vertex(&mut self) -> VertexId {
        LabeledVertex::add_vertex(self, ())
    }
}

impl<L: PartialEq> DiGraph<L> {
    /// Returns the identifier of a vertex having given label.
    pub fn vertex(&self, label: &L) -> Option<VertexId> {
        self.labels.iter().position(|l| l == label).map(VertexId)
    }
}

impl<L: Copy> DiGraph<L> {
    /// Copies and returns all labels associated with the given vertices.
    #[must_use]
    pub fn copied_labels(&self, vertices: impl AsRef<[VertexId]>) -> Vec<L> {
        vertices
            .as_ref()
            .iter()
            .filter_map(|&id| self.labels.get(id.0))
            .copied()
            .collect()
    }
}

impl<L: Clone> DiGraph<L> {
    /// Clones and returns all labels associated with the given vertices.
    #[must_use]
    pub fn cloned_labels(&self, vertices: impl AsRef<[VertexId]>) -> Vec<L> {
        vertices
            .as_ref()
            .iter()
            .filter_map(|&id| self.labels.get(id.0))
            .cloned()
            .collect()
    }
}

impl<L> DiGraph<L> {
    /// Creates an empty graph.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            successors: Vec::new(),
            predecessors: Vec::new(),
            labels: Vec::new(),
        }
    }

    /// Creates a directed edge between vertices.
    pub fn add_edge(&mut self, source: VertexId, sink: VertexId) -> bool {
        if source.0 < self.successors.len() && sink.0 < self.predecessors.len() {
            self.predecessors[sink.0].push(source.0);
            self.successors[source.0].push(sink.0);
            true
        } else {
            false
        }
    }

    /// Returns iterator over labels for given vertices.
    pub fn labels(&self, vertices: &[VertexId]) -> impl Iterator<Item = &L> {
        vertices.iter().filter_map(|&id| self.labels.get(id.0))
    }

    /// Returns `true` when a graph is acyclic.
    #[must_use]
    pub fn is_acyclic(&self) -> bool {
        self.analyze().1.iter().all(|&deg| deg == 0)
    }

    /// Returns the first found cycle.
    #[must_use]
    pub fn cycle(&self) -> Option<Vec<VertexId>> {
        let (_, degree) = self.analyze();
        let id = degree.iter().position(|&deg| deg > 0)?;
        Some(self.build(id, &degree))
    }

    /// Returns topologically sorted vertices when the graph is acyclic.
    ///
    /// # Errors
    ///
    /// When the graph is not acyclic, returns the first found cycle.
    pub fn sort(&self) -> Result<Vec<VertexId>, Vec<VertexId>> {
        let (sorted, degree) = self.analyze();
        degree
            .iter()
            .position(|&deg| deg > 0)
            .map_or(Ok(sorted), |id| Err(self.build(id, &degree)))
    }

    /// Builds a cycle starting from a given vertex.
    fn build(&self, mut id: usize, degree: &[usize]) -> Vec<VertexId> {
        let mut position: Vec<Option<usize>> = vec![None; degree.len()];
        position[id] = Some(0);
        let mut cycle = vec![VertexId(id)];
        let mut predecessor;
        loop {
            predecessor = self.predecessors[id]
                .iter()
                .find(|&i| degree[*i] > 0)
                .copied()
                .unwrap();
            if position[predecessor].is_some() {
                break;
            }
            position[predecessor] = Some(cycle.len());
            cycle.push(VertexId(predecessor));
            id = predecessor;
        }
        cycle.drain(..position[predecessor].unwrap());
        cycle.reverse();
        cycle
    }

    /// Analyzes the graph using Kahn's algorithm.
    fn analyze(&self) -> (Vec<VertexId>, Vec<usize>) {
        let count = self.predecessors.len();
        let mut sorted = Vec::with_capacity(count);
        let mut starting = vec![];
        let mut remaining = vec![];
        let mut degree: Vec<usize> = self.predecessors.iter().map(Vec::len).collect();
        for (i, p) in self.predecessors.iter().enumerate() {
            if p.is_empty() {
                starting.push(i);
            }
        }
        while !starting.is_empty() {
            for &i in &starting {
                sorted.push(VertexId(i));
                for &j in &self.successors[i] {
                    degree[j] -= 1;
                    if degree[j] == 0 {
                        remaining.push(j);
                    }
                }
            }
            starting.clear();
            std::mem::swap(&mut starting, &mut remaining);
        }
        (sorted, degree)
    }
}