1 //! Generate files suitable for use with [Graphviz](http://www.graphviz.org/)
3 //! The `render` function generates output (e.g., an `output.dot` file) for
4 //! use with [Graphviz](http://www.graphviz.org/) by walking a labeled
5 //! graph. (Graphviz can then automatically lay out the nodes and edges
6 //! of the graph, and also optionally render the graph as an image or
7 //! other [output formats](
8 //! http://www.graphviz.org/content/output-formats), such as SVG.)
10 //! Rather than impose some particular graph data structure on clients,
11 //! this library exposes two traits that clients can implement on their
12 //! own structs before handing them over to the rendering function.
14 //! Note: This library does not yet provide access to the full
15 //! expressiveness of the [DOT language](
16 //! http://www.graphviz.org/doc/info/lang.html). For example, there are
17 //! many [attributes](http://www.graphviz.org/content/attrs) related to
18 //! providing layout hints (e.g., left-to-right versus top-down, which
19 //! algorithm to use, etc). The current intention of this library is to
20 //! emit a human-readable .dot file with very regular structure suitable
21 //! for easy post-processing.
25 //! The first example uses a very simple graph representation: a list of
26 //! pairs of ints, representing the edges (the node set is implicit).
27 //! Each node label is derived directly from the int representing the node,
28 //! while the edge labels are all empty strings.
30 //! This example also illustrates how to use `Cow<[T]>` to return
31 //! an owned vector or a borrowed slice as appropriate: we construct the
32 //! node vector from scratch, but borrow the edge list (rather than
33 //! constructing a copy of all the edges from scratch).
35 //! The output from this example renders five nodes, with the first four
36 //! forming a diamond-shaped acyclic graph and then pointing to the fifth
40 //! #![feature(rustc_private)]
42 //! use std::io::Write;
43 //! use graphviz as dot;
46 //! type Ed = (isize,isize);
47 //! struct Edges(Vec<Ed>);
49 //! pub fn render_to<W: Write>(output: &mut W) {
50 //! let edges = Edges(vec![(0,1), (0,2), (1,3), (2,3), (3,4), (4,4)]);
51 //! dot::render(&edges, output).unwrap()
54 //! impl<'a> dot::Labeller<'a> for Edges {
57 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example1").unwrap() }
59 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
60 //! dot::Id::new(format!("N{}", *n)).unwrap()
64 //! impl<'a> dot::GraphWalk<'a> for Edges {
67 //! fn nodes(&self) -> dot::Nodes<'a,Nd> {
68 //! // (assumes that |N| \approxeq |E|)
69 //! let &Edges(ref v) = self;
70 //! let mut nodes = Vec::with_capacity(v.len());
72 //! nodes.push(s); nodes.push(t);
79 //! fn edges(&'a self) -> dot::Edges<'a,Ed> {
80 //! let &Edges(ref edges) = self;
81 //! (&edges[..]).into()
84 //! fn source(&self, e: &Ed) -> Nd { let &(s,_) = e; s }
86 //! fn target(&self, e: &Ed) -> Nd { let &(_,t) = e; t }
89 //! # pub fn main() { render_to(&mut Vec::new()) }
93 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
95 //! use std::fs::File;
96 //! let mut f = File::create("example1.dot").unwrap();
101 //! Output from first example (in `example1.dot`):
104 //! digraph example1 {
110 //! N0 -> N1[label=""];
111 //! N0 -> N2[label=""];
112 //! N1 -> N3[label=""];
113 //! N2 -> N3[label=""];
114 //! N3 -> N4[label=""];
115 //! N4 -> N4[label=""];
119 //! The second example illustrates using `node_label` and `edge_label` to
120 //! add labels to the nodes and edges in the rendered graph. The graph
121 //! here carries both `nodes` (the label text to use for rendering a
122 //! particular node), and `edges` (again a list of `(source,target)`
125 //! This example also illustrates how to use a type (in this case the edge
126 //! type) that shares substructure with the graph: the edge type here is a
127 //! direct reference to the `(source,target)` pair stored in the graph's
128 //! internal vector (rather than passing around a copy of the pair
129 //! itself). Note that this implies that `fn edges(&'a self)` must
130 //! construct a fresh `Vec<&'a (usize,usize)>` from the `Vec<(usize,usize)>`
131 //! edges stored in `self`.
133 //! Since both the set of nodes and the set of edges are always
134 //! constructed from scratch via iterators, we use the `collect()` method
135 //! from the `Iterator` trait to collect the nodes and edges into freshly
136 //! constructed growable `Vec` values (rather than using `Cow` as in the
137 //! first example above).
139 //! The output from this example renders four nodes that make up the
140 //! Hasse-diagram for the subsets of the set `{x, y}`. Each edge is
141 //! labeled with the ⊆ character (specified using the HTML character
145 //! #![feature(rustc_private)]
147 //! use std::io::Write;
148 //! use graphviz as dot;
151 //! type Ed<'a> = &'a (usize, usize);
152 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
154 //! pub fn render_to<W: Write>(output: &mut W) {
155 //! let nodes = vec!["{x,y}","{x}","{y}","{}"];
156 //! let edges = vec![(0,1), (0,2), (1,3), (2,3)];
157 //! let graph = Graph { nodes: nodes, edges: edges };
159 //! dot::render(&graph, output).unwrap()
162 //! impl<'a> dot::Labeller<'a> for Graph {
164 //! type Edge = Ed<'a>;
165 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example2").unwrap() }
166 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
167 //! dot::Id::new(format!("N{}", n)).unwrap()
169 //! fn node_label<'b>(&'b self, n: &Nd) -> dot::LabelText<'b> {
170 //! dot::LabelText::LabelStr(self.nodes[*n].into())
172 //! fn edge_label<'b>(&'b self, _: &Ed) -> dot::LabelText<'b> {
173 //! dot::LabelText::LabelStr("⊆".into())
177 //! impl<'a> dot::GraphWalk<'a> for Graph {
179 //! type Edge = Ed<'a>;
180 //! fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() }
181 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> { self.edges.iter().collect() }
182 //! fn source(&self, e: &Ed) -> Nd { let & &(s,_) = e; s }
183 //! fn target(&self, e: &Ed) -> Nd { let & &(_,t) = e; t }
186 //! # pub fn main() { render_to(&mut Vec::new()) }
190 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
192 //! use std::fs::File;
193 //! let mut f = File::create("example2.dot").unwrap();
194 //! render_to(&mut f)
198 //! The third example is similar to the second, except now each node and
199 //! edge now carries a reference to the string label for each node as well
200 //! as that node's index. (This is another illustration of how to share
201 //! structure with the graph itself, and why one might want to do so.)
203 //! The output from this example is the same as the second example: the
204 //! Hasse-diagram for the subsets of the set `{x, y}`.
207 //! #![feature(rustc_private)]
209 //! use std::io::Write;
210 //! use graphviz as dot;
212 //! type Nd<'a> = (usize, &'a str);
213 //! type Ed<'a> = (Nd<'a>, Nd<'a>);
214 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
216 //! pub fn render_to<W: Write>(output: &mut W) {
217 //! let nodes = vec!["{x,y}","{x}","{y}","{}"];
218 //! let edges = vec![(0,1), (0,2), (1,3), (2,3)];
219 //! let graph = Graph { nodes: nodes, edges: edges };
221 //! dot::render(&graph, output).unwrap()
224 //! impl<'a> dot::Labeller<'a> for Graph {
225 //! type Node = Nd<'a>;
226 //! type Edge = Ed<'a>;
227 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() }
228 //! fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> {
229 //! dot::Id::new(format!("N{}", n.0)).unwrap()
231 //! fn node_label<'b>(&'b self, n: &Nd<'b>) -> dot::LabelText<'b> {
233 //! dot::LabelText::LabelStr(self.nodes[i].into())
235 //! fn edge_label<'b>(&'b self, _: &Ed<'b>) -> dot::LabelText<'b> {
236 //! dot::LabelText::LabelStr("⊆".into())
240 //! impl<'a> dot::GraphWalk<'a> for Graph {
241 //! type Node = Nd<'a>;
242 //! type Edge = Ed<'a>;
243 //! fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
244 //! self.nodes.iter().map(|s| &s[..]).enumerate().collect()
246 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
247 //! self.edges.iter()
248 //! .map(|&(i,j)|((i, &self.nodes[i][..]),
249 //! (j, &self.nodes[j][..])))
252 //! fn source(&self, e: &Ed<'a>) -> Nd<'a> { let &(s,_) = e; s }
253 //! fn target(&self, e: &Ed<'a>) -> Nd<'a> { let &(_,t) = e; t }
256 //! # pub fn main() { render_to(&mut Vec::new()) }
260 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
262 //! use std::fs::File;
263 //! let mut f = File::create("example3.dot").unwrap();
264 //! render_to(&mut f)
270 //! * [Graphviz](http://www.graphviz.org/)
272 //! * [DOT language](http://www.graphviz.org/doc/info/lang.html)
274 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
275 test(attr(allow(unused_variables), deny(warnings))))]
277 #![deny(rust_2018_idioms)]
280 #![feature(str_escape)]
284 use std::borrow::Cow;
285 use std::io::prelude::*;
288 /// The text for a graphviz label on a node or edge.
289 pub enum LabelText<'a> {
290 /// This kind of label preserves the text directly as is.
292 /// Occurrences of backslashes (`\`) are escaped, and thus appear
293 /// as backslashes in the rendered label.
294 LabelStr(Cow<'a, str>),
296 /// This kind of label uses the graphviz label escString type:
297 /// <http://www.graphviz.org/content/attrs#kescString>
299 /// Occurrences of backslashes (`\`) are not escaped; instead they
300 /// are interpreted as initiating an escString escape sequence.
302 /// Escape sequences of particular interest: in addition to `\n`
303 /// to break a line (centering the line preceding the `\n`), there
304 /// are also the escape sequences `\l` which left-justifies the
305 /// preceding line and `\r` which right-justifies it.
306 EscStr(Cow<'a, str>),
308 /// This uses a graphviz [HTML string label][html]. The string is
309 /// printed exactly as given, but between `<` and `>`. **No
310 /// escaping is performed.**
312 /// [html]: http://www.graphviz.org/content/node-shapes#html
313 HtmlStr(Cow<'a, str>),
316 /// The style for a node or edge.
317 /// See <http://www.graphviz.org/doc/info/attrs.html#k:style> for descriptions.
318 /// Note that some of these are not valid for edges.
319 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
334 pub fn as_slice(self) -> &'static str {
337 Style::Solid => "solid",
338 Style::Dashed => "dashed",
339 Style::Dotted => "dotted",
340 Style::Bold => "bold",
341 Style::Rounded => "rounded",
342 Style::Diagonals => "diagonals",
343 Style::Filled => "filled",
344 Style::Striped => "striped",
345 Style::Wedged => "wedged",
350 // There is a tension in the design of the labelling API.
352 // For example, I considered making a `Labeller<T>` trait that
353 // provides labels for `T`, and then making the graph type `G`
354 // implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
355 // not possible without functional dependencies. (One could work
356 // around that, but I did not explore that avenue heavily.)
358 // Another approach that I actually used for a while was to make a
359 // `Label<Context>` trait that is implemented by the client-specific
360 // Node and Edge types (as well as an implementation on Graph itself
361 // for the overall name for the graph). The main disadvantage of this
362 // second approach (compared to having the `G` type parameter
363 // implement a Labelling service) that I have encountered is that it
364 // makes it impossible to use types outside of the current crate
365 // directly as Nodes/Edges; you need to wrap them in newtype'd
366 // structs. See e.g., the `No` and `Ed` structs in the examples. (In
367 // practice clients using a graph in some other crate would need to
368 // provide some sort of adapter shim over the graph anyway to
369 // interface with this library).
371 // Another approach would be to make a single `Labeller<N,E>` trait
372 // that provides three methods (graph_label, node_label, edge_label),
373 // and then make `G` implement `Labeller<N,E>`. At first this did not
374 // appeal to me, since I had thought I would need separate methods on
375 // each data variant for dot-internal identifiers versus user-visible
376 // labels. However, the identifier/label distinction only arises for
377 // nodes; graphs themselves only have identifiers, and edges only have
380 // So in the end I decided to use the third approach described above.
382 /// `Id` is a Graphviz `ID`.
388 /// Creates an `Id` named `name`.
390 /// The caller must ensure that the input conforms to an
391 /// identifier format: it must be a non-empty string made up of
392 /// alphanumeric or underscore characters, not beginning with a
393 /// digit (i.e., the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
395 /// (Note: this format is a strict subset of the `ID` format
396 /// defined by the DOT language. This function may change in the
397 /// future to accept a broader subset, or the entirety, of DOT's
400 /// Passing an invalid string (containing spaces, brackets,
401 /// quotes, ...) will return an empty `Err` value.
402 pub fn new<Name: Into<Cow<'a, str>>>(name: Name) -> Result<Id<'a>, ()> {
403 let name = name.into();
404 match name.chars().next() {
405 Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
408 if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' ) {
415 pub fn as_slice(&'a self) -> &'a str {
419 pub fn name(self) -> Cow<'a, str> {
424 /// Each instance of a type that implements `Label<C>` maps to a
425 /// unique identifier with respect to `C`, which is used to identify
426 /// it in the generated .dot file. They can also provide more
427 /// elaborate (and non-unique) label text that is used in the graphviz
430 /// The graph instance is responsible for providing the DOT compatible
431 /// identifiers for the nodes and (optionally) rendered labels for the nodes and
432 /// edges, as well as an identifier for the graph itself.
433 pub trait Labeller<'a> {
437 /// Must return a DOT compatible identifier naming the graph.
438 fn graph_id(&'a self) -> Id<'a>;
440 /// Maps `n` to a unique identifier with respect to `self`. The
441 /// implementor is responsible for ensuring that the returned name
442 /// is a valid DOT identifier.
443 fn node_id(&'a self, n: &Self::Node) -> Id<'a>;
445 /// Maps `n` to one of the [graphviz `shape` names][1]. If `None`
446 /// is returned, no `shape` attribute is specified.
448 /// [1]: http://www.graphviz.org/content/node-shapes
449 fn node_shape(&'a self, _node: &Self::Node) -> Option<LabelText<'a>> {
453 /// Maps `n` to a label that will be used in the rendered output.
454 /// The label need not be unique, and may be the empty string; the
455 /// default is just the output from `node_id`.
456 fn node_label(&'a self, n: &Self::Node) -> LabelText<'a> {
457 LabelStr(self.node_id(n).name)
460 /// Maps `e` to a label that will be used in the rendered output.
461 /// The label need not be unique, and may be the empty string; the
462 /// default is in fact the empty string.
463 fn edge_label(&'a self, _e: &Self::Edge) -> LabelText<'a> {
467 /// Maps `n` to a style that will be used in the rendered output.
468 fn node_style(&'a self, _n: &Self::Node) -> Style {
472 /// Maps `e` to a style that will be used in the rendered output.
473 fn edge_style(&'a self, _e: &Self::Edge) -> Style {
478 /// Escape tags in such a way that it is suitable for inclusion in a
479 /// Graphviz HTML label.
480 pub fn escape_html(s: &str) -> String {
481 s.replace("&", "&")
482 .replace("\"", """)
483 .replace("<", "<")
484 .replace(">", ">")
487 impl<'a> LabelText<'a> {
488 pub fn label<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
492 pub fn escaped<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
496 pub fn html<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
500 fn escape_char<F>(c: char, mut f: F)
504 // not escaping \\, since Graphviz escString needs to
505 // interpret backslashes; see EscStr above.
508 for c in c.escape_default() {
514 fn escape_str(s: &str) -> String {
515 let mut out = String::with_capacity(s.len());
517 LabelText::escape_char(c, |c| out.push(c));
522 /// Renders text as string suitable for a label in a .dot file.
523 /// This includes quotes or suitable delimiters.
524 pub fn to_dot_string(&self) -> String {
526 LabelStr(ref s) => format!("\"{}\"", s.escape_default()),
527 EscStr(ref s) => format!("\"{}\"", LabelText::escape_str(&s)),
528 HtmlStr(ref s) => format!("<{}>", s),
532 /// Decomposes content into string suitable for making EscStr that
533 /// yields same content as self. The result obeys the law
534 /// render(`lt`) == render(`EscStr(lt.pre_escaped_content())`) for
535 /// all `lt: LabelText`.
536 fn pre_escaped_content(self) -> Cow<'a, str> {
540 if s.contains('\\') {
541 (&*s).escape_default().into()
550 /// Puts `prefix` on a line above this label, with a blank line separator.
551 pub fn prefix_line(self, prefix: LabelText<'_>) -> LabelText<'static> {
552 prefix.suffix_line(self)
555 /// Puts `suffix` on a line below this label, with a blank line separator.
556 pub fn suffix_line(self, suffix: LabelText<'_>) -> LabelText<'static> {
557 let mut prefix = self.pre_escaped_content().into_owned();
558 let suffix = suffix.pre_escaped_content();
559 prefix.push_str(r"\n\n");
560 prefix.push_str(&suffix);
561 EscStr(prefix.into())
565 pub type Nodes<'a,N> = Cow<'a,[N]>;
566 pub type Edges<'a,E> = Cow<'a,[E]>;
568 // (The type parameters in GraphWalk should be associated items,
569 // when/if Rust supports such.)
571 /// GraphWalk is an abstraction over a directed graph = (nodes,edges)
572 /// made up of node handles `N` and edge handles `E`, where each `E`
573 /// can be mapped to its source and target nodes.
575 /// The lifetime parameter `'a` is exposed in this trait (rather than
576 /// introduced as a generic parameter on each method declaration) so
577 /// that a client impl can choose `N` and `E` that have substructure
578 /// that is bound by the self lifetime `'a`.
580 /// The `nodes` and `edges` method each return instantiations of
581 /// `Cow<[T]>` to leave implementors the freedom to create
582 /// entirely new vectors or to pass back slices into internally owned
584 pub trait GraphWalk<'a> {
588 /// Returns all the nodes in this graph.
589 fn nodes(&'a self) -> Nodes<'a, Self::Node>;
590 /// Returns all of the edges in this graph.
591 fn edges(&'a self) -> Edges<'a, Self::Edge>;
592 /// The source node for `edge`.
593 fn source(&'a self, edge: &Self::Edge) -> Self::Node;
594 /// The target node for `edge`.
595 fn target(&'a self, edge: &Self::Edge) -> Self::Node;
598 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
599 pub enum RenderOption {
606 /// Returns vec holding all the default render options.
607 pub fn default_options() -> Vec<RenderOption> {
611 /// Renders directed graph `g` into the writer `w` in DOT syntax.
612 /// (Simple wrapper around `render_opts` that passes a default set of options.)
613 pub fn render<'a,N,E,G,W>(g: &'a G, w: &mut W) -> io::Result<()>
616 G: Labeller<'a, Node=N, Edge=E> + GraphWalk<'a, Node=N, Edge=E>,
619 render_opts(g, w, &[])
622 /// Renders directed graph `g` into the writer `w` in DOT syntax.
623 /// (Main entry point for the library.)
624 pub fn render_opts<'a, N, E, G, W>(g: &'a G,
626 options: &[RenderOption])
630 G: Labeller<'a, Node=N, Edge=E> + GraphWalk<'a, Node=N, Edge=E>,
633 writeln!(w, "digraph {} {{", g.graph_id().as_slice())?;
634 for n in g.nodes().iter() {
636 let id = g.node_id(n);
638 let escaped = &g.node_label(n).to_dot_string();
640 let mut text = Vec::new();
641 write!(text, "{}", id.as_slice()).unwrap();
643 if !options.contains(&RenderOption::NoNodeLabels) {
644 write!(text, "[label={}]", escaped).unwrap();
647 let style = g.node_style(n);
648 if !options.contains(&RenderOption::NoNodeStyles) && style != Style::None {
649 write!(text, "[style=\"{}\"]", style.as_slice()).unwrap();
652 if let Some(s) = g.node_shape(n) {
653 write!(text, "[shape={}]", &s.to_dot_string()).unwrap();
656 writeln!(text, ";").unwrap();
657 w.write_all(&text[..])?;
660 for e in g.edges().iter() {
661 let escaped_label = &g.edge_label(e).to_dot_string();
663 let source = g.source(e);
664 let target = g.target(e);
665 let source_id = g.node_id(&source);
666 let target_id = g.node_id(&target);
668 let mut text = Vec::new();
669 write!(text, "{} -> {}", source_id.as_slice(), target_id.as_slice()).unwrap();
671 if !options.contains(&RenderOption::NoEdgeLabels) {
672 write!(text, "[label={}]", escaped_label).unwrap();
675 let style = g.edge_style(e);
676 if !options.contains(&RenderOption::NoEdgeStyles) && style != Style::None {
677 write!(text, "[style=\"{}\"]", style.as_slice()).unwrap();
680 writeln!(text, ";").unwrap();
681 w.write_all(&text[..])?;
690 use super::{Id, Labeller, Nodes, Edges, GraphWalk, render, Style};
691 use super::LabelText::{self, LabelStr, EscStr, HtmlStr};
693 use std::io::prelude::*;
695 /// each node is an index in a vector in the graph.
704 fn edge(from: usize, to: usize, label: &'static str, style: Style) -> Edge {
713 struct LabelledGraph {
714 /// The name for this graph. Used for labeling generated `digraph`.
717 /// Each node is an index into `node_labels`; these labels are
718 /// used as the label text for each node. (The node *names*,
719 /// which are unique identifiers, are derived from their index
722 /// If a node maps to None here, then just use its name as its
724 node_labels: Vec<Option<&'static str>>,
726 node_styles: Vec<Style>,
728 /// Each edge relates a from-index to a to-index along with a
729 /// label; `edges` collects them.
733 // A simple wrapper around LabelledGraph that forces the labels to
734 // be emitted as EscStr.
735 struct LabelledGraphWithEscStrs {
736 graph: LabelledGraph,
740 AllNodesLabelled(Vec<L>),
741 UnlabelledNodes(usize),
742 SomeNodesLabelled(Vec<Option<L>>),
745 type Trivial = NodeLabels<&'static str>;
747 impl NodeLabels<&'static str> {
748 fn to_opt_strs(self) -> Vec<Option<&'static str>> {
750 UnlabelledNodes(len) => vec![None; len],
751 AllNodesLabelled(lbls) => lbls.into_iter().map(|l| Some(l)).collect(),
752 SomeNodesLabelled(lbls) => lbls.into_iter().collect(),
756 fn len(&self) -> usize {
758 &UnlabelledNodes(len) => len,
759 &AllNodesLabelled(ref lbls) => lbls.len(),
760 &SomeNodesLabelled(ref lbls) => lbls.len(),
766 fn new(name: &'static str,
767 node_labels: Trivial,
769 node_styles: Option<Vec<Style>>)
771 let count = node_labels.len();
774 node_labels: node_labels.to_opt_strs(),
776 node_styles: match node_styles {
777 Some(nodes) => nodes,
778 None => vec![Style::None; count],
784 impl LabelledGraphWithEscStrs {
785 fn new(name: &'static str,
786 node_labels: Trivial,
788 -> LabelledGraphWithEscStrs {
789 LabelledGraphWithEscStrs { graph: LabelledGraph::new(name, node_labels, edges, None) }
793 fn id_name<'a>(n: &Node) -> Id<'a> {
794 Id::new(format!("N{}", *n)).unwrap()
797 impl<'a> Labeller<'a> for LabelledGraph {
799 type Edge = &'a Edge;
800 fn graph_id(&'a self) -> Id<'a> {
801 Id::new(self.name).unwrap()
803 fn node_id(&'a self, n: &Node) -> Id<'a> {
806 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
807 match self.node_labels[*n] {
808 Some(l) => LabelStr(l.into()),
809 None => LabelStr(id_name(n).name()),
812 fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
813 LabelStr(e.label.into())
815 fn node_style(&'a self, n: &Node) -> Style {
818 fn edge_style(&'a self, e: &&'a Edge) -> Style {
823 impl<'a> Labeller<'a> for LabelledGraphWithEscStrs {
825 type Edge = &'a Edge;
826 fn graph_id(&'a self) -> Id<'a> {
827 self.graph.graph_id()
829 fn node_id(&'a self, n: &Node) -> Id<'a> {
830 self.graph.node_id(n)
832 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
833 match self.graph.node_label(n) {
834 LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
837 fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
838 match self.graph.edge_label(e) {
839 LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
844 impl<'a> GraphWalk<'a> for LabelledGraph {
846 type Edge = &'a Edge;
847 fn nodes(&'a self) -> Nodes<'a, Node> {
848 (0..self.node_labels.len()).collect()
850 fn edges(&'a self) -> Edges<'a, &'a Edge> {
851 self.edges.iter().collect()
853 fn source(&'a self, edge: &&'a Edge) -> Node {
856 fn target(&'a self, edge: &&'a Edge) -> Node {
861 impl<'a> GraphWalk<'a> for LabelledGraphWithEscStrs {
863 type Edge = &'a Edge;
864 fn nodes(&'a self) -> Nodes<'a, Node> {
867 fn edges(&'a self) -> Edges<'a, &'a Edge> {
870 fn source(&'a self, edge: &&'a Edge) -> Node {
873 fn target(&'a self, edge: &&'a Edge) -> Node {
878 fn test_input(g: LabelledGraph) -> io::Result<String> {
879 let mut writer = Vec::new();
880 render(&g, &mut writer).unwrap();
881 let mut s = String::new();
882 Read::read_to_string(&mut &*writer, &mut s)?;
886 // All of the tests use raw-strings as the format for the expected outputs,
887 // so that you can cut-and-paste the content into a .dot file yourself to
888 // see what the graphviz visualizer would produce.
892 let labels: Trivial = UnlabelledNodes(0);
893 let r = test_input(LabelledGraph::new("empty_graph", labels, vec![], None));
894 assert_eq!(r.unwrap(),
895 r#"digraph empty_graph {
902 let labels: Trivial = UnlabelledNodes(1);
903 let r = test_input(LabelledGraph::new("single_node", labels, vec![], None));
904 assert_eq!(r.unwrap(),
905 r#"digraph single_node {
912 fn single_node_with_style() {
913 let labels: Trivial = UnlabelledNodes(1);
914 let styles = Some(vec![Style::Dashed]);
915 let r = test_input(LabelledGraph::new("single_node", labels, vec![], styles));
916 assert_eq!(r.unwrap(),
917 r#"digraph single_node {
918 N0[label="N0"][style="dashed"];
925 let labels: Trivial = UnlabelledNodes(2);
926 let result = test_input(LabelledGraph::new("single_edge",
928 vec![edge(0, 1, "E", Style::None)],
930 assert_eq!(result.unwrap(),
931 r#"digraph single_edge {
940 fn single_edge_with_style() {
941 let labels: Trivial = UnlabelledNodes(2);
942 let result = test_input(LabelledGraph::new("single_edge",
944 vec![edge(0, 1, "E", Style::Bold)],
946 assert_eq!(result.unwrap(),
947 r#"digraph single_edge {
950 N0 -> N1[label="E"][style="bold"];
956 fn test_some_labelled() {
957 let labels: Trivial = SomeNodesLabelled(vec![Some("A"), None]);
958 let styles = Some(vec![Style::None, Style::Dotted]);
959 let result = test_input(LabelledGraph::new("test_some_labelled",
961 vec![edge(0, 1, "A-1", Style::None)],
963 assert_eq!(result.unwrap(),
964 r#"digraph test_some_labelled {
966 N1[label="N1"][style="dotted"];
967 N0 -> N1[label="A-1"];
973 fn single_cyclic_node() {
974 let labels: Trivial = UnlabelledNodes(1);
975 let r = test_input(LabelledGraph::new("single_cyclic_node",
977 vec![edge(0, 0, "E", Style::None)],
979 assert_eq!(r.unwrap(),
980 r#"digraph single_cyclic_node {
989 let labels = AllNodesLabelled(vec!["{x,y}", "{x}", "{y}", "{}"]);
990 let r = test_input(LabelledGraph::new("hasse_diagram",
992 vec![edge(0, 1, "", Style::None),
993 edge(0, 2, "", Style::None),
994 edge(1, 3, "", Style::None),
995 edge(2, 3, "", Style::None)],
997 assert_eq!(r.unwrap(),
998 r#"digraph hasse_diagram {
1012 fn left_aligned_text() {
1013 let labels = AllNodesLabelled(vec![
1025 let mut writer = Vec::new();
1027 let g = LabelledGraphWithEscStrs::new("syntax_tree",
1029 vec![edge(0, 1, "then", Style::None),
1030 edge(0, 2, "else", Style::None),
1031 edge(1, 3, ";", Style::None),
1032 edge(2, 3, ";", Style::None)]);
1034 render(&g, &mut writer).unwrap();
1035 let mut r = String::new();
1036 Read::read_to_string(&mut &*writer, &mut r).unwrap();
1039 r#"digraph syntax_tree {
1040 N0[label="if test {\l branch1\l} else {\l branch2\l}\lafterward\l"];
1041 N1[label="branch1"];
1042 N2[label="branch2"];
1043 N3[label="afterward"];
1044 N0 -> N1[label="then"];
1045 N0 -> N2[label="else"];
1046 N1 -> N3[label=";"];
1047 N2 -> N3[label=";"];
1053 fn simple_id_construction() {
1054 let id1 = Id::new("hello");
1057 Err(..) => panic!("'hello' is not a valid value for id anymore"),
1062 fn badly_formatted_id() {
1063 let id2 = Id::new("Weird { struct : ure } !!!");
1065 Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),