Add a simple graphviz .dot output function
diff --git a/src/lib.rs b/src/lib.rs
index ac09b05..7674eec 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -28,6 +28,7 @@
pub mod algo;
pub mod graphmap;
pub mod graph;
+pub mod parse;
pub mod visit;
pub mod unionfind;
diff --git a/src/parse.rs b/src/parse.rs
new file mode 100644
index 0000000..03d9b97
--- /dev/null
+++ b/src/parse.rs
@@ -0,0 +1,59 @@
+
+use std::fmt;
+use super::Graph;
+use super::EdgeType;
+use super::graph::IndexType;
+
+/// Wrapper implementing formatting to graphviz .dot format for a graph.
+#[derive(Copy, Clone, Debug)]
+pub struct DisplayDot<'a, G: 'a> {
+ graph: &'a G,
+}
+
+static TYPE: [&'static str; 2] = ["graph", "digraph"];
+static EDGE: [&'static str; 2] = ["--", "->"];
+static INDENT: &'static str = " ";
+
+impl<'a, G> DisplayDot<'a, G>
+{
+ pub fn new(graph: &'a G) -> Self {
+ DisplayDot {
+ graph: graph,
+ }
+ }
+}
+
+impl<'a, N, E, Ty, Ix> fmt::Display for DisplayDot<'a, Graph<N, E, Ty, Ix>> where
+ N: fmt::Display,
+ E: fmt::Display,
+ Ty: EdgeType,
+ Ix: IndexType,
+{
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
+ {
+ let g = self.graph;
+ try!(writeln!(f, "{} {{", TYPE[g.is_directed() as usize]));
+
+ // output all labels
+ for (index, node) in g.raw_nodes().iter().enumerate() {
+ try!(writeln!(f, "{}N{} [label=\"{}\"]",
+ INDENT, index, node.weight));
+
+ }
+ // output all edges
+ for edge in g.raw_edges().iter() {
+ try!(writeln!(f, "{}N{} {} N{} [label=\"{}\"]",
+ INDENT,
+ edge.source().index(),
+ EDGE[g.is_directed() as usize],
+ edge.target().index(),
+ edge.weight));
+
+ }
+
+ // node name is "N%d"
+ try!(writeln!(f, "}}"));
+ Ok(())
+ }
+}
+
diff --git a/tests/ograph.rs b/tests/ograph.rs
index 8531504..1f0befa 100644
--- a/tests/ograph.rs
+++ b/tests/ograph.rs
@@ -14,6 +14,8 @@
Undirected,
};
+use petgraph::parse::DisplayDot;
+
use petgraph::algo::{
min_spanning_tree,
is_cyclic_undirected,
@@ -83,6 +85,8 @@
gr.add_edge(i, j, 1.);
gr.add_edge(i, k, 2.);
+ println!("{}", DisplayDot::new(&gr));
+
/*
assert_eq!(DfsIter::new(&gr, h).count(), 4);
@@ -172,7 +176,10 @@
gr.add_edge(h, j, 3.);
gr.add_edge(i, j, 1.);
+ println!("{}", DisplayDot::new(&gr));
+
let mst = min_spanning_tree(&gr);
+ println!("{}", DisplayDot::new(&mst));
println!("MST is:\n{:?}", mst);
assert!(mst.node_count() == gr.node_count());
// |E| = |N| - 2 because there are two disconnected components.