Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "dagis"
version = "0.1.0"
version = "0.2.0"
authors = ["Dariusz Depta <depta@engos.de>"]
description = "A fast directed acyclic graph (DAG) checker"
documentation = "https://docs.rs/dagis"
Expand Down
106 changes: 0 additions & 106 deletions src/di_graph.rs

This file was deleted.

182 changes: 182 additions & 0 deletions src/graphs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
/// 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)
}
}
6 changes: 2 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
#![deny(rustdoc::missing_crate_level_docs)]
#![doc = include_str!("../docs/lib.rs.md")]

mod di_graph;
mod typed_di_graph;
mod graphs;

pub use di_graph::DiGraph;
pub use typed_di_graph::TypedDiGraph;
pub use graphs::{DiGraph, LabeledVertex, VertexId};
48 changes: 0 additions & 48 deletions src/typed_di_graph.rs

This file was deleted.

Loading
Loading