dot3/
lib.rs

1// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! Generate files suitable for use with [Graphviz](https://graphviz.org/)
12//!
13//! The `render` function generates output (e.g. an `output.dot` file) for
14//! use with [Graphviz](https://graphviz.org/) by walking a labelled
15//! graph. (Graphviz can then automatically lay out the nodes and edges
16//! of the graph, and also optionally render the graph as an image or
17//! other [output formats](https://graphviz.org/docs/outputs), such as SVG.)
18//!
19//! Rather than impose some particular graph data structure on clients,
20//! this library exposes two traits that clients can implement on their
21//! own structs before handing them over to the rendering function.
22//!
23//! Note: This library does not yet provide access to the full
24//! expressiveness of the [DOT language](https://graphviz.org/doc/info/lang.html).
25//! For example, there are many [attributes](https://graphviz.org/doc/info/attrs.html)
26//! related to providing layout hints (e.g. left-to-right versus top-down, which
27//! algorithm to use, etc). The current intention of this library is to
28//! emit a human-readable .dot file with very regular structure suitable
29//! for easy post-processing.
30//!
31//! # Examples
32//!
33//! The first example uses a very simple graph representation: a list of
34//! pairs of ints, representing the edges (the node set is implicit).
35//! Each node label is derived directly from the int representing the node,
36//! while the edge labels are all empty strings.
37//!
38//! This example also illustrates how to use `Cow<[T]>` to return
39//! an owned vector or a borrowed slice as appropriate: we construct the
40//! node vector from scratch, but borrow the edge list (rather than
41//! constructing a copy of all the edges from scratch).
42//!
43//! The output from this example renders five nodes, with the first four
44//! forming a diamond-shaped acyclic graph and then pointing to the fifth
45//! which is cyclic.
46//!
47//! ```rust
48//! use std::borrow::Cow;
49//! use std::io::Write;
50//!
51//! type Nd = isize;
52//! type Ed = (isize,isize);
53//! struct Edges(Vec<Ed>);
54//!
55//! pub fn render_to<W: Write>(output: &mut W) {
56//!     let edges = Edges(vec!((0,1), (0,2), (1,3), (2,3), (3,4), (4,4)));
57//!     dot::render(&edges, output).unwrap()
58//! }
59//!
60//! impl<'a> dot::Labeller<'a, Nd, Ed> for Edges {
61//!     fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example1").unwrap() }
62//!
63//!     fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
64//!         dot::Id::new(format!("N{}", *n)).unwrap()
65//!     }
66//! }
67//!
68//! impl<'a> dot::GraphWalk<'a, Nd, Ed> for Edges {
69//!     fn nodes(&self) -> dot::Nodes<'a,Nd> {
70//!         // (assumes that |N| \approxeq |E|)
71//!         let &Edges(ref v) = self;
72//!         let mut nodes = Vec::with_capacity(v.len());
73//!         for &(s,t) in v {
74//!             nodes.push(s); nodes.push(t);
75//!         }
76//!         nodes.sort();
77//!         nodes.dedup();
78//!         Cow::Owned(nodes)
79//!     }
80//!
81//!     fn edges(&'a self) -> dot::Edges<'a,Ed> {
82//!         let &Edges(ref edges) = self;
83//!         Cow::Borrowed(&edges[..])
84//!     }
85//!
86//!     fn source(&self, e: &Ed) -> Nd { e.0 }
87//!
88//!     fn target(&self, e: &Ed) -> Nd { e.1 }
89//! }
90//!
91//! # pub fn main() { render_to(&mut Vec::new()) }
92//! ```
93//!
94//! ```no_run
95//! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
96//! pub fn main() {
97//!     use std::fs::File;
98//!     let mut f = File::create("example1.dot").unwrap();
99//!     render_to(&mut f)
100//! }
101//! ```
102//!
103//! Output from first example (in `example1.dot`):
104//!
105//! ```ignore
106//! digraph example1 {
107//!     N0[label="N0"];
108//!     N1[label="N1"];
109//!     N2[label="N2"];
110//!     N3[label="N3"];
111//!     N4[label="N4"];
112//!     N0 -> N1[label=""];
113//!     N0 -> N2[label=""];
114//!     N1 -> N3[label=""];
115//!     N2 -> N3[label=""];
116//!     N3 -> N4[label=""];
117//!     N4 -> N4[label=""];
118//! }
119//! ```
120//!
121//! The second example illustrates using `node_label` and `edge_label` to
122//! add labels to the nodes and edges in the rendered graph. The graph
123//! here carries both `nodes` (the label text to use for rendering a
124//! particular node), and `edges` (again a list of `(source,target)`
125//! indices).
126//!
127//! This example also illustrates how to use a type (in this case the edge
128//! type) that shares substructure with the graph: the edge type here is a
129//! direct reference to the `(source,target)` pair stored in the graph's
130//! internal vector (rather than passing around a copy of the pair
131//! itself). Note that this implies that `fn edges(&'a self)` must
132//! construct a fresh `Vec<&'a (usize,usize)>` from the `Vec<(usize,usize)>`
133//! edges stored in `self`.
134//!
135//! Since both the set of nodes and the set of edges are always
136//! constructed from scratch via iterators, we use the `collect()` method
137//! from the `Iterator` trait to collect the nodes and edges into freshly
138//! constructed growable `Vec` values (rather use the `into`
139//! from the `IntoCow` trait as was used in the first example
140//! above).
141//!
142//! The output from this example renders four nodes that make up the
143//! Hasse-diagram for the subsets of the set `{x, y}`. Each edge is
144//! labelled with the &sube; character (specified using the HTML character
145//! entity `&sube`).
146//!
147//! ```rust
148//! use std::io::Write;
149//!
150//! type Nd = usize;
151//! type Ed<'a> = &'a (usize, usize);
152//! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
153//!
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 };
158//!
159//!     dot::render(&graph, output).unwrap()
160//! }
161//!
162//! impl<'a> dot::Labeller<'a, Nd, Ed<'a>> for Graph {
163//!     fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example2").unwrap() }
164//!     fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
165//!         dot::Id::new(format!("N{}", n)).unwrap()
166//!     }
167//!     fn node_label<'b>(&'b self, n: &Nd) -> dot::LabelText<'b> {
168//!         dot::LabelText::LabelStr(self.nodes[*n].into())
169//!     }
170//!     fn edge_label<'b>(&'b self, _: &Ed) -> dot::LabelText<'b> {
171//!         dot::LabelText::LabelStr("&sube;".into())
172//!     }
173//! }
174//!
175//! impl<'a> dot::GraphWalk<'a, Nd, Ed<'a>> for Graph {
176//!     fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() }
177//!     fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> { self.edges.iter().collect() }
178//!     fn source(&self, e: &Ed) -> Nd { e.0 }
179//!     fn target(&self, e: &Ed) -> Nd { e.1 }
180//! }
181//!
182//! # pub fn main() { render_to(&mut Vec::new()) }
183//! ```
184//!
185//! ```no_run
186//! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
187//! pub fn main() {
188//!     use std::fs::File;
189//!     let mut f = File::create("example2.dot").unwrap();
190//!     render_to(&mut f)
191//! }
192//! ```
193//!
194//! The third example is similar to the second, except now each node and
195//! edge now carries a reference to the string label for each node as well
196//! as that node's index. (This is another illustration of how to share
197//! structure with the graph itself, and why one might want to do so.)
198//!
199//! The output from this example is the same as the second example: the
200//! Hasse-diagram for the subsets of the set `{x, y}`.
201//!
202//! ```rust
203//! use std::io::Write;
204//!
205//! type Nd<'a> = (usize, &'a str);
206//! type Ed<'a> = (Nd<'a>, Nd<'a>);
207//! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
208//!
209//! pub fn render_to<W: Write>(output: &mut W) {
210//!     let nodes = vec!("{x,y}","{x}","{y}","{}");
211//!     let edges = vec!((0,1), (0,2), (1,3), (2,3));
212//!     let graph = Graph { nodes: nodes, edges: edges };
213//!
214//!     dot::render(&graph, output).unwrap()
215//! }
216//!
217//! impl<'a> dot::Labeller<'a, Nd<'a>, Ed<'a>> for Graph {
218//!     fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() }
219//!     fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> {
220//!         dot::Id::new(format!("N{}", n.0)).unwrap()
221//!     }
222//!     fn node_label<'b>(&'b self, n: &Nd<'b>) -> dot::LabelText<'b> {
223//!         let &(i, _) = n;
224//!         dot::LabelText::LabelStr(self.nodes[i].into())
225//!     }
226//!     fn edge_label<'b>(&'b self, _: &Ed<'b>) -> dot::LabelText<'b> {
227//!         dot::LabelText::LabelStr("&sube;".into())
228//!     }
229//! }
230//!
231//! impl<'a> dot::GraphWalk<'a, Nd<'a>, Ed<'a>> for Graph {
232//!     fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
233//!         self.nodes.iter().map(|s| &s[..]).enumerate().collect()
234//!     }
235//!     fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
236//!         self.edges.iter()
237//!             .map(|&(i,j)|((i, &self.nodes[i][..]),
238//!                           (j, &self.nodes[j][..])))
239//!             .collect()
240//!     }
241//!     fn source(&self, e: &Ed<'a>) -> Nd<'a> { e.0 }
242//!     fn target(&self, e: &Ed<'a>) -> Nd<'a> { e.1 }
243//! }
244//!
245//! # pub fn main() { render_to(&mut Vec::new()) }
246//! ```
247//!
248//! ```no_run
249//! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
250//! pub fn main() {
251//!     use std::fs::File;
252//!     let mut f = File::create("example3.dot").unwrap();
253//!     render_to(&mut f)
254//! }
255//! ```
256//!
257//! # References
258//!
259//! * [Graphviz](https://graphviz.org/)
260//!
261//! * [DOT language](https://graphviz.org/doc/info/lang.html)
262
263#![crate_name = "dot3"]
264#![crate_type = "rlib"]
265#![crate_type = "dylib"]
266#![doc(
267    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
268    html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
269    html_root_url = "https://doc.rust-lang.org/nightly/"
270)]
271
272use self::LabelText::*;
273
274use std::borrow::Cow;
275use std::collections::HashMap;
276use std::io;
277use std::io::prelude::*;
278
279/// The text for a graphviz label on a node or edge.
280pub enum LabelText<'a> {
281    /// This kind of label preserves the text directly as is.
282    ///
283    /// Occurrences of backslashes (`\`) are escaped, and thus appear
284    /// as backslashes in the rendered label.
285    LabelStr(Cow<'a, str>),
286
287    /// This kind of label uses the graphviz label escString type:
288    /// https://graphviz.org/docs/attr-types/escString
289    ///
290    /// Occurrences of backslashes (`\`) are not escaped; instead they
291    /// are interpreted as initiating an escString escape sequence.
292    ///
293    /// Escape sequences of particular interest: in addition to `\n`
294    /// to break a line (centering the line preceding the `\n`), there
295    /// are also the escape sequences `\l` which left-justifies the
296    /// preceding line and `\r` which right-justifies it.
297    EscStr(Cow<'a, str>),
298
299    /// This uses a graphviz [HTML string label][html]. The string is
300    /// printed exactly as given, but between `<` and `>`. **No
301    /// escaping is performed.**
302    ///
303    /// [html]: https://graphviz.org/doc/info/shapes.html#html
304    HtmlStr(Cow<'a, str>),
305}
306
307/// The style for a node or edge.
308/// See https://graphviz.org/doc/info/attrs.html#k:style for descriptions.
309/// Note that some of these are not valid for edges.
310#[derive(Copy, Clone, PartialEq, Eq, Debug)]
311pub enum Style {
312    None,
313    Solid,
314    Dashed,
315    Dotted,
316    Bold,
317    Rounded,
318    Diagonals,
319    Filled,
320    Striped,
321    Wedged,
322}
323
324impl Style {
325    pub fn as_slice(self) -> &'static str {
326        match self {
327            Style::None => "",
328            Style::Solid => "solid",
329            Style::Dashed => "dashed",
330            Style::Dotted => "dotted",
331            Style::Bold => "bold",
332            Style::Rounded => "rounded",
333            Style::Diagonals => "diagonals",
334            Style::Filled => "filled",
335            Style::Striped => "striped",
336            Style::Wedged => "wedged",
337        }
338    }
339}
340
341/// The direction to draw directed graphs (one rank at a time)
342/// See https://graphviz.org/docs/attr-types/rankdir/ for descriptions
343#[derive(Copy, Clone, PartialEq, Eq, Debug)]
344pub enum RankDir {
345    TopBottom,
346    LeftRight,
347    BottomTop,
348    RightLeft,
349}
350
351impl RankDir {
352    pub fn as_slice(self) -> &'static str {
353        match self {
354            RankDir::TopBottom => "TB",
355            RankDir::LeftRight => "LR",
356            RankDir::BottomTop => "BT",
357            RankDir::RightLeft => "RL",
358        }
359    }
360}
361
362// There is a tension in the design of the labelling API.
363//
364// For example, I considered making a `Labeller<T>` trait that
365// provides labels for `T`, and then making the graph type `G`
366// implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
367// not possible without functional dependencies. (One could work
368// around that, but I did not explore that avenue heavily.)
369//
370// Another approach that I actually used for a while was to make a
371// `Label<Context>` trait that is implemented by the client-specific
372// Node and Edge types (as well as an implementation on Graph itself
373// for the overall name for the graph). The main disadvantage of this
374// second approach (compared to having the `G` type parameter
375// implement a Labelling service) that I have encountered is that it
376// makes it impossible to use types outside of the current crate
377// directly as Nodes/Edges; you need to wrap them in newtype'd
378// structs. See e.g. the `No` and `Ed` structs in the examples. (In
379// practice clients using a graph in some other crate would need to
380// provide some sort of adapter shim over the graph anyway to
381// interface with this library).
382//
383// Another approach would be to make a single `Labeller<N,E>` trait
384// that provides three methods (graph_label, node_label, edge_label),
385// and then make `G` implement `Labeller<N,E>`. At first this did not
386// appeal to me, since I had thought I would need separate methods on
387// each data variant for dot-internal identifiers versus user-visible
388// labels. However, the identifier/label distinction only arises for
389// nodes; graphs themselves only have identifiers, and edges only have
390// labels.
391//
392// So in the end I decided to use the third approach described above.
393
394/// `Id` is a Graphviz `ID`.
395pub struct Id<'a> {
396    name: Cow<'a, str>,
397}
398
399#[derive(Debug)]
400pub enum IdError {
401    EmptyName,
402    InvalidStartChar(char),
403    InvalidChar(char),
404}
405
406impl std::fmt::Display for IdError {
407    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408        match self {
409            IdError::EmptyName => write!(f, "Id cannot be empty"),
410            IdError::InvalidStartChar(c) => write!(f, "Id cannot begin with '{c}'"),
411            IdError::InvalidChar(c) => write!(f, "Id cannot contain '{c}'"),
412        }
413    }
414}
415impl std::error::Error for IdError {}
416
417impl<'a> Id<'a> {
418    /// Creates an `Id` named `name`.
419    ///
420    /// The caller must ensure that the input conforms to an
421    /// identifier format: it must be a non-empty string made up of
422    /// alphanumeric or underscore characters, not beginning with a
423    /// digit (i.e. the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
424    ///
425    /// (Note: this format is a strict subset of the `ID` format
426    /// defined by the DOT language.  This function may change in the
427    /// future to accept a broader subset, or the entirety, of DOT's
428    /// `ID` format.)
429    ///
430    /// Passing an invalid string (containing spaces, brackets,
431    /// quotes, ...) will return an empty `Err` value.
432    pub fn new<Name: Into<Cow<'a, str>>>(name: Name) -> Result<Id<'a>, IdError> {
433        let name = name.into();
434        {
435            let mut chars = name.chars();
436            match chars.next() {
437                Some(c) if is_letter_or_underscore(c) => {}
438                Some(c) => return Err(IdError::InvalidStartChar(c)),
439                _ => return Err(IdError::EmptyName),
440            }
441            if let Some(bad) = chars.find(|c| !is_constituent(*c)) {
442                return Err(IdError::InvalidChar(bad));
443            }
444        }
445        return Ok(Id { name });
446
447        fn is_letter_or_underscore(c: char) -> bool {
448            in_range('a', c, 'z') || in_range('A', c, 'Z') || c == '_'
449        }
450        fn is_constituent(c: char) -> bool {
451            is_letter_or_underscore(c) || in_range('0', c, '9')
452        }
453        fn in_range(low: char, c: char, high: char) -> bool {
454            low as usize <= c as usize && c as usize <= high as usize
455        }
456    }
457
458    pub fn as_slice(&'a self) -> &'a str {
459        &*self.name
460    }
461
462    pub fn name(self) -> Cow<'a, str> {
463        self.name
464    }
465}
466
467/// Each instance of a type that implements `Label<C>` maps to a
468/// unique identifier with respect to `C`, which is used to identify
469/// it in the generated .dot file. They can also provide more
470/// elaborate (and non-unique) label text that is used in the graphviz
471/// rendered output.
472
473/// The graph instance is responsible for providing the DOT compatible
474/// identifiers for the nodes and (optionally) rendered labels for the nodes and
475/// edges, as well as an identifier for the graph itself.
476pub trait Labeller<'a, N, E> {
477    /// Must return a DOT compatible identifier naming the graph.
478    fn graph_id(&'a self) -> Id<'a>;
479
480    /// A list of attributes to apply to the graph
481    fn graph_attrs(&'a self) -> HashMap<&str, &str> {
482        HashMap::default()
483    }
484
485    /// Maps `n` to a unique identifier with respect to `self`. The
486    /// implementer is responsible for ensuring that the returned name
487    /// is a valid DOT identifier.
488    fn node_id(&'a self, n: &N) -> Id<'a>;
489
490    /// Maps `n` to one of the [graphviz `shape` names][1]. If `None`
491    /// is returned, no `shape` attribute is specified.
492    ///
493    /// [1]: https://graphviz.org/doc/info/shapes.html
494    fn node_shape(&'a self, _node: &N) -> Option<LabelText<'a>> {
495        None
496    }
497
498    /// Maps `n` to a label that will be used in the rendered output.
499    /// The label need not be unique, and may be the empty string; the
500    /// default is just the output from `node_id`.
501    fn node_label(&'a self, n: &N) -> LabelText<'a> {
502        LabelStr(self.node_id(n).name())
503    }
504
505    /// Maps `e` to a label that will be used in the rendered output.
506    /// The label need not be unique, and may be the empty string; the
507    /// default is in fact the empty string.
508    fn edge_label(&'a self, e: &E) -> LabelText<'a> {
509        let _ignored = e;
510        LabelStr("".into())
511    }
512
513    /// Maps `n` to a style that will be used in the rendered output.
514    fn node_style(&'a self, _n: &N) -> Style {
515        Style::None
516    }
517
518    /// Return an explicit rank dir to use for directed graphs.
519    ///
520    /// Return 'None' to use the default (generally "TB" for directed graphs).
521    fn rank_dir(&'a self) -> Option<RankDir> {
522        None
523    }
524
525    /// Maps `n` to one of the [graphviz `color` names][1]. If `None`
526    /// is returned, no `color` attribute is specified.
527    ///
528    /// [1]: https://graphviz.gitlab.io/_pages/doc/info/colors.html
529    fn node_color(&'a self, _node: &N) -> Option<LabelText<'a>> {
530        None
531    }
532
533    /// Maps `n` to a set of arbritrary node attributes.
534    fn node_attrs(&'a self, _n: &N) -> HashMap<&str, &str> {
535        HashMap::default()
536    }
537
538    /// Maps `e` to arrow style that will be used on the end of an edge.
539    /// Defaults to default arrow style.
540    fn edge_end_arrow(&'a self, _e: &E) -> Arrow {
541        Arrow::default()
542    }
543
544    /// Maps `e` to arrow style that will be used on the end of an edge.
545    /// Defaults to default arrow style.
546    fn edge_start_arrow(&'a self, _e: &E) -> Arrow {
547        Arrow::default()
548    }
549
550    /// Maps `e` to a style that will be used in the rendered output.
551    fn edge_style(&'a self, _e: &E) -> Style {
552        Style::None
553    }
554
555    /// Maps `e` to one of the [graphviz `color` names][1]. If `None`
556    /// is returned, no `color` attribute is specified.
557    ///
558    /// [1]: https://graphviz.gitlab.io/_pages/doc/info/colors.html
559    fn edge_color(&'a self, _e: &E) -> Option<LabelText<'a>> {
560        None
561    }
562
563    /// Maps `e` to a set of arbritrary edge attributes.
564    fn edge_attrs(&'a self, _e: &E) -> HashMap<&str, &str> {
565        HashMap::default()
566    }
567
568    /// The kind of graph, defaults to `Kind::Digraph`.
569    #[inline]
570    fn kind(&self) -> Kind {
571        Kind::Digraph
572    }
573
574    /// Maps `e` to the compass point that the edge will start from.
575    /// Defaults to the default point
576    fn edge_start_point(&'a self, _e: &E) -> Option<CompassPoint> {
577        None
578    }
579
580    /// Maps `e` to the compass point that the edge will end at.
581    /// Defaults to the default point
582    fn edge_end_point(&'a self, _e: &E) -> Option<CompassPoint> {
583        None
584    }
585
586    /// Maps `e` to the port that the edge will start from.
587    fn edge_start_port(&'a self, _: &E) -> Option<Id<'a>> {
588        None
589    }
590
591    /// Maps `e` to the port that the edge will end at.
592    fn edge_end_port(&'a self, _: &E) -> Option<Id<'a>> {
593        None
594    }
595}
596
597pub enum CompassPoint {
598    North,
599    NorthEast,
600    East,
601    SouthEast,
602    South,
603    SouthWest,
604    West,
605    NorthWest,
606    Center,
607}
608
609impl CompassPoint {
610    const fn to_code(&self) -> &'static str {
611        use CompassPoint::*;
612        match self {
613            North => ":n",
614            NorthEast => ":ne",
615            East => ":e",
616            SouthEast => ":se",
617            South => ":s",
618            SouthWest => ":sw",
619            West => ":w",
620            NorthWest => ":nw",
621            Center => ":c",
622        }
623    }
624}
625
626/// Escape tags in such a way that it is suitable for inclusion in a
627/// Graphviz HTML label.
628pub fn escape_html(s: &str) -> String {
629    s.replace('&', "&amp;")
630        .replace('"', "&quot;")
631        .replace('<', "&lt;")
632        .replace('>', "&gt;")
633}
634
635impl<'a> LabelText<'a> {
636    pub fn label<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
637        LabelStr(s.into())
638    }
639
640    pub fn escaped<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
641        EscStr(s.into())
642    }
643
644    pub fn html<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
645        HtmlStr(s.into())
646    }
647
648    fn escape_char<F>(c: char, mut f: F)
649    where
650        F: FnMut(char),
651    {
652        match c {
653            // not escaping \\, since Graphviz escString needs to
654            // interpret backslashes; see EscStr above.
655            '\\' => f(c),
656            _ => {
657                for c in c.escape_default() {
658                    f(c)
659                }
660            }
661        }
662    }
663    fn escape_str(s: &str) -> String {
664        let mut out = String::with_capacity(s.len());
665        for c in s.chars() {
666            LabelText::escape_char(c, |c| out.push(c));
667        }
668        out
669    }
670
671    fn escape_default(s: &str) -> String {
672        s.chars().flat_map(|c| c.escape_default()).collect()
673    }
674
675    /// Renders text as string suitable for a label in a .dot file.
676    /// This includes quotes or suitable delimeters.
677    pub fn to_dot_string(&self) -> String {
678        match self {
679            LabelStr(ref s) => format!("\"{}\"", LabelText::escape_default(s)),
680            EscStr(ref s) => format!("\"{}\"", LabelText::escape_str(&s[..])),
681            HtmlStr(ref s) => format!("<{}>", s),
682        }
683    }
684
685    /// Decomposes content into string suitable for making EscStr that
686    /// yields same content as self.  The result obeys the law
687    /// render(`lt`) == render(`EscStr(lt.pre_escaped_content())`) for
688    /// all `lt: LabelText`.
689    fn pre_escaped_content(self) -> Cow<'a, str> {
690        match self {
691            EscStr(s) => s,
692            LabelStr(s) => {
693                if s.contains('\\') {
694                    LabelText::escape_default(&*s).into()
695                } else {
696                    s
697                }
698            }
699            HtmlStr(s) => s,
700        }
701    }
702
703    /// Puts `prefix` on a line above this label, with a blank line separator.
704    pub fn prefix_line(self, prefix: LabelText) -> LabelText<'static> {
705        prefix.suffix_line(self)
706    }
707
708    /// Puts `suffix` on a line below this label, with a blank line separator.
709    pub fn suffix_line(self, suffix: LabelText) -> LabelText<'static> {
710        let mut prefix = self.pre_escaped_content().into_owned();
711        let suffix = suffix.pre_escaped_content();
712        prefix.push_str(r"\n\n");
713        prefix.push_str(&suffix[..]);
714        EscStr(prefix.into())
715    }
716}
717
718/// This structure holds all information that can describe an arrow connected to
719/// either start or end of an edge.
720#[derive(Clone, Hash, PartialEq, Eq)]
721pub struct Arrow {
722    pub arrows: Vec<ArrowShape>,
723}
724
725use self::ArrowShape::*;
726
727impl Arrow {
728    /// Return `true` if this is a default arrow.
729    fn is_default(&self) -> bool {
730        self.arrows.is_empty()
731    }
732
733    /// Arrow constructor which returns a default arrow
734    pub fn default() -> Arrow {
735        Arrow { arrows: vec![] }
736    }
737
738    /// Arrow constructor which returns an empty arrow
739    pub fn none() -> Arrow {
740        Arrow {
741            arrows: vec![NoArrow],
742        }
743    }
744
745    /// Arrow constructor which returns a regular triangle arrow, without modifiers
746    pub fn normal() -> Arrow {
747        Arrow {
748            arrows: vec![ArrowShape::normal()],
749        }
750    }
751
752    /// Arrow constructor which returns an arrow created by a given ArrowShape.
753    pub fn from_arrow(arrow: ArrowShape) -> Arrow {
754        Arrow {
755            arrows: vec![arrow],
756        }
757    }
758
759    /// Function which converts given arrow into a renderable form.
760    pub fn to_dot_string(&self) -> String {
761        let mut cow = String::new();
762        for arrow in &self.arrows {
763            cow.push_str(&arrow.to_dot_string());
764        }
765        cow
766    }
767}
768
769macro_rules! arrowshape_to_arrow {
770    ($n:expr) => {
771        impl From<[ArrowShape; $n]> for Arrow {
772            fn from(shape: [ArrowShape; $n]) -> Arrow {
773                Arrow {
774                    arrows: shape.to_vec(),
775                }
776            }
777        }
778    };
779}
780arrowshape_to_arrow!(2);
781arrowshape_to_arrow!(3);
782arrowshape_to_arrow!(4);
783
784/// Arrow modifier that determines if the shape is empty or filled.
785#[derive(Clone, Copy, Hash, PartialEq, Eq)]
786pub enum Fill {
787    Open,
788    Filled,
789}
790
791impl Fill {
792    pub fn as_slice(self) -> &'static str {
793        match self {
794            Fill::Open => "o",
795            Fill::Filled => "",
796        }
797    }
798}
799
800/// Arrow modifier that determines if the shape is clipped.
801/// For example `Side::Left` means only left side is visible.
802#[derive(Clone, Copy, Hash, PartialEq, Eq)]
803pub enum Side {
804    Left,
805    Right,
806    Both,
807}
808
809impl Side {
810    pub fn as_slice(self) -> &'static str {
811        match self {
812            Side::Left => "l",
813            Side::Right => "r",
814            Side::Both => "",
815        }
816    }
817}
818
819/// This enumeration represents all possible arrow edge
820/// as defined in [graphviz documentation](https://graphviz.org/doc/info/arrows.html).
821#[derive(Clone, Copy, Hash, PartialEq, Eq)]
822pub enum ArrowShape {
823    /// No arrow will be displayed
824    NoArrow,
825    /// Arrow that ends in a triangle. Basically a normal arrow.
826    /// NOTE: there is error in official documentation, this supports both fill and side clipping
827    Normal(Fill, Side),
828    /// Arrow ending in a small square box
829    Box(Fill, Side),
830    /// Arrow ending in a three branching lines also called crow's foot
831    Crow(Side),
832    /// Arrow ending in a curve
833    Curve(Side),
834    /// Arrow ending in an inverted curve
835    ICurve(Fill, Side),
836    /// Arrow ending in an diamond shaped rectangular shape.
837    Diamond(Fill, Side),
838    /// Arrow ending in a circle.
839    Dot(Fill),
840    /// Arrow ending in an inverted triangle.
841    Inv(Fill, Side),
842    /// Arrow ending with a T shaped arrow.
843    Tee(Side),
844    /// Arrow ending with a V shaped arrow.
845    Vee(Side),
846}
847impl ArrowShape {
848    /// Constructor which returns no arrow.
849    pub fn none() -> ArrowShape {
850        ArrowShape::NoArrow
851    }
852
853    /// Constructor which returns normal arrow.
854    pub fn normal() -> ArrowShape {
855        ArrowShape::Normal(Fill::Filled, Side::Both)
856    }
857
858    /// Constructor which returns a regular box arrow.
859    pub fn boxed() -> ArrowShape {
860        ArrowShape::Box(Fill::Filled, Side::Both)
861    }
862
863    /// Constructor which returns a regular crow arrow.
864    pub fn crow() -> ArrowShape {
865        ArrowShape::Crow(Side::Both)
866    }
867
868    /// Constructor which returns a regular curve arrow.
869    pub fn curve() -> ArrowShape {
870        ArrowShape::Curve(Side::Both)
871    }
872
873    /// Constructor which returns an inverted curve arrow.
874    pub fn icurve() -> ArrowShape {
875        ArrowShape::ICurve(Fill::Filled, Side::Both)
876    }
877
878    /// Constructor which returns a diamond arrow.
879    pub fn diamond() -> ArrowShape {
880        ArrowShape::Diamond(Fill::Filled, Side::Both)
881    }
882
883    /// Constructor which returns a circle shaped arrow.
884    pub fn dot() -> ArrowShape {
885        ArrowShape::Diamond(Fill::Filled, Side::Both)
886    }
887
888    /// Constructor which returns an inverted triangle arrow.
889    pub fn inv() -> ArrowShape {
890        ArrowShape::Inv(Fill::Filled, Side::Both)
891    }
892
893    /// Constructor which returns a T shaped arrow.
894    pub fn tee() -> ArrowShape {
895        ArrowShape::Tee(Side::Both)
896    }
897
898    /// Constructor which returns a V shaped arrow.
899    pub fn vee() -> ArrowShape {
900        ArrowShape::Vee(Side::Both)
901    }
902
903    /// Function which renders given ArrowShape into a String for displaying.
904    pub fn to_dot_string(&self) -> String {
905        let mut res = String::new();
906        match *self {
907            Box(fill, side)
908            | ICurve(fill, side)
909            | Diamond(fill, side)
910            | Inv(fill, side)
911            | Normal(fill, side) => {
912                res.push_str(fill.as_slice());
913                match side {
914                    Side::Left | Side::Right => res.push_str(side.as_slice()),
915                    Side::Both => {}
916                };
917            }
918            Dot(fill) => res.push_str(fill.as_slice()),
919            Crow(side) | Curve(side) | Tee(side) | Vee(side) => match side {
920                Side::Left | Side::Right => res.push_str(side.as_slice()),
921                Side::Both => {}
922            },
923            NoArrow => {}
924        };
925        match *self {
926            NoArrow => res.push_str("none"),
927            Normal(_, _) => res.push_str("normal"),
928            Box(_, _) => res.push_str("box"),
929            Crow(_) => res.push_str("crow"),
930            Curve(_) => res.push_str("curve"),
931            ICurve(_, _) => res.push_str("icurve"),
932            Diamond(_, _) => res.push_str("diamond"),
933            Dot(_) => res.push_str("dot"),
934            Inv(_, _) => res.push_str("inv"),
935            Tee(_) => res.push_str("tee"),
936            Vee(_) => res.push_str("vee"),
937        };
938        res
939    }
940}
941
942pub type Nodes<'a, N> = Cow<'a, [N]>;
943pub type Edges<'a, E> = Cow<'a, [E]>;
944
945/// Graph kind determines if `digraph` or `graph` is used as keyword
946/// for the graph.
947#[derive(Copy, Clone, PartialEq, Eq, Debug)]
948pub enum Kind {
949    Digraph,
950    Graph,
951}
952
953impl Kind {
954    /// The keyword to use to introduce the graph.
955    /// Determines which edge syntax must be used, and default style.
956    fn keyword(&self) -> &'static str {
957        match *self {
958            Kind::Digraph => "digraph",
959            Kind::Graph => "graph",
960        }
961    }
962
963    /// The edgeop syntax to use for this graph kind.
964    fn edgeop(&self) -> &'static str {
965        match *self {
966            Kind::Digraph => "->",
967            Kind::Graph => "--",
968        }
969    }
970}
971
972// (The type parameters in GraphWalk should be associated items,
973// when/if Rust supports such.)
974
975/// GraphWalk is an abstraction over a graph = (nodes,edges)
976/// made up of node handles `N` and edge handles `E`, where each `E`
977/// can be mapped to its source and target nodes.
978///
979/// The lifetime parameter `'a` is exposed in this trait (rather than
980/// introduced as a generic parameter on each method declaration) so
981/// that a client impl can choose `N` and `E` that have substructure
982/// that is bound by the self lifetime `'a`.
983///
984/// The `nodes` and `edges` method each return instantiations of
985/// `Cow<[T]>` to leave implementers the freedom to create
986/// entirely new vectors or to pass back slices into internally owned
987/// vectors.
988pub trait GraphWalk<'a, N: Clone, E: Clone> {
989    /// Returns all the nodes in this graph.
990    fn nodes(&'a self) -> Nodes<'a, N>;
991    /// Returns all of the edges in this graph.
992    fn edges(&'a self) -> Edges<'a, E>;
993    /// The source node for `edge`.
994    fn source(&'a self, edge: &E) -> N;
995    /// The target node for `edge`.
996    fn target(&'a self, edge: &E) -> N;
997}
998
999#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1000pub enum RenderOption {
1001    NoEdgeLabels,
1002    NoNodeLabels,
1003    NoEdgeStyles,
1004    NoEdgeColors,
1005    NoNodeStyles,
1006    NoNodeColors,
1007    NoArrows,
1008}
1009
1010/// Returns vec holding all the default render options.
1011pub fn default_options() -> Vec<RenderOption> {
1012    vec![]
1013}
1014
1015/// Renders graph `g` into the writer `w` in DOT syntax.
1016/// (Simple wrapper around `render_opts` that passes a default set of options.)
1017pub fn render<
1018    'a,
1019    N: Clone + 'a,
1020    E: Clone + 'a,
1021    G: Labeller<'a, N, E> + GraphWalk<'a, N, E>,
1022    W: Write,
1023>(
1024    g: &'a G,
1025    w: &mut W,
1026) -> io::Result<()> {
1027    render_opts(g, w, &[])
1028}
1029
1030/// Renders graph `g` into the writer `w` in DOT syntax.
1031/// (Main entry point for the library.)
1032pub fn render_opts<
1033    'a,
1034    N: Clone + 'a,
1035    E: Clone + 'a,
1036    G: Labeller<'a, N, E> + GraphWalk<'a, N, E>,
1037    W: Write,
1038>(
1039    g: &'a G,
1040    w: &mut W,
1041    options: &[RenderOption],
1042) -> io::Result<()> {
1043    fn writeln<W: Write>(w: &mut W, arg: &[&str]) -> io::Result<()> {
1044        for &s in arg {
1045            w.write_all(s.as_bytes())?;
1046        }
1047        writeln!(w)
1048    }
1049
1050    fn indent<W: Write>(w: &mut W) -> io::Result<()> {
1051        w.write_all(b"    ")
1052    }
1053
1054    writeln(w, &[g.kind().keyword(), " ", g.graph_id().as_slice(), " {"])?;
1055    for (name, value) in g.graph_attrs().iter() {
1056        writeln(w, &[name, "=", value])?;
1057    }
1058
1059    if g.kind() == Kind::Digraph {
1060        if let Some(rankdir) = g.rank_dir() {
1061            indent(w)?;
1062            writeln(w, &["rankdir=\"", rankdir.as_slice(), "\";"])?;
1063        }
1064    }
1065
1066    for n in g.nodes().iter() {
1067        let colorstring;
1068
1069        indent(w)?;
1070        let id = g.node_id(n);
1071
1072        let escaped = &g.node_label(n).to_dot_string();
1073        let shape;
1074
1075        let mut text = vec![id.as_slice()];
1076
1077        if !options.contains(&RenderOption::NoNodeLabels) {
1078            text.push("[label=");
1079            text.push(escaped);
1080            text.push("]");
1081        }
1082
1083        let style = g.node_style(n);
1084        if !options.contains(&RenderOption::NoNodeStyles) && style != Style::None {
1085            text.push("[style=\"");
1086            text.push(style.as_slice());
1087            text.push("\"]");
1088        }
1089
1090        let color = g.node_color(n);
1091        if !options.contains(&RenderOption::NoNodeColors) {
1092            if let Some(c) = color {
1093                colorstring = c.to_dot_string();
1094                text.push("[color=");
1095                text.push(&colorstring);
1096                text.push("]");
1097            }
1098        }
1099
1100        if let Some(s) = g.node_shape(n) {
1101            shape = s.to_dot_string();
1102            text.push("[shape=");
1103            text.push(&shape);
1104            text.push("]");
1105        }
1106
1107        let node_attrs = g
1108            .node_attrs(n)
1109            .iter()
1110            .map(|(name, value)| format!("[{name}={value}]"))
1111            .collect::<Vec<String>>();
1112        text.extend(node_attrs.iter().map(|s| s as &str));
1113
1114        text.push(";");
1115        writeln(w, &text)?;
1116    }
1117
1118    for e in g.edges().iter() {
1119        let colorstring;
1120        let escaped_label = &g.edge_label(e).to_dot_string();
1121        let start_arrow = g.edge_start_arrow(e);
1122        let end_arrow = g.edge_end_arrow(e);
1123        let start_arrow_s = start_arrow.to_dot_string();
1124        let end_arrow_s = end_arrow.to_dot_string();
1125        let start_port = g
1126            .edge_start_port(e)
1127            .map(|p| format!(":{}", p.name()))
1128            .unwrap_or_default();
1129        let end_port = g
1130            .edge_end_port(e)
1131            .map(|p| format!(":{}", p.name()))
1132            .unwrap_or_default();
1133        let start_p = g.edge_start_point(e).map(|p| p.to_code()).unwrap_or("");
1134        let end_p = g.edge_end_point(e).map(|p| p.to_code()).unwrap_or("");
1135
1136        indent(w)?;
1137        let source = g.source(e);
1138        let target = g.target(e);
1139        let source_id = g.node_id(&source);
1140        let target_id = g.node_id(&target);
1141
1142        let mut text = vec![
1143            source_id.as_slice(),
1144            &start_port,
1145            start_p,
1146            " ",
1147            g.kind().edgeop(),
1148            " ",
1149            target_id.as_slice(),
1150            &end_port,
1151            end_p,
1152        ];
1153
1154        if !options.contains(&RenderOption::NoEdgeLabels) {
1155            text.push("[label=");
1156            text.push(escaped_label);
1157            text.push("]");
1158        }
1159
1160        let style = g.edge_style(e);
1161        if !options.contains(&RenderOption::NoEdgeStyles) && style != Style::None {
1162            text.push("[style=\"");
1163            text.push(style.as_slice());
1164            text.push("\"]");
1165        }
1166
1167        let color = g.edge_color(e);
1168        if !options.contains(&RenderOption::NoEdgeColors) {
1169            if let Some(c) = color {
1170                colorstring = c.to_dot_string();
1171                text.push("[color=");
1172                text.push(&colorstring);
1173                text.push("]");
1174            }
1175        }
1176
1177        if !options.contains(&RenderOption::NoArrows)
1178            && (!start_arrow.is_default() || !end_arrow.is_default())
1179        {
1180            text.push("[");
1181            if !end_arrow.is_default() {
1182                text.push("arrowhead=\"");
1183                text.push(&end_arrow_s);
1184                text.push("\"");
1185            }
1186            if !start_arrow.is_default() {
1187                text.push(" dir=\"both\" arrowtail=\"");
1188                text.push(&start_arrow_s);
1189                text.push("\"");
1190            }
1191
1192            text.push("]");
1193        }
1194        let edge_attrs = g
1195            .edge_attrs(e)
1196            .iter()
1197            .map(|(name, value)| format!("[{name}={value}]"))
1198            .collect::<Vec<String>>();
1199        text.extend(edge_attrs.iter().map(|s| s as &str));
1200        text.push(";");
1201        writeln(w, &text)?;
1202    }
1203
1204    writeln(w, &["}"])
1205}
1206
1207#[cfg(test)]
1208mod tests {
1209    use self::NodeLabels::*;
1210    use super::LabelText::{self, EscStr, HtmlStr, LabelStr};
1211    use super::{render, Edges, GraphWalk, Id, Kind, Labeller, Nodes, RankDir, Style};
1212    use super::{Arrow, ArrowShape, Side};
1213    use std::io;
1214    use std::io::prelude::*;
1215
1216    /// each node is an index in a vector in the graph.
1217    type Node = usize;
1218    struct Edge {
1219        from: usize,
1220        to: usize,
1221        label: &'static str,
1222        style: Style,
1223        start_arrow: Arrow,
1224        end_arrow: Arrow,
1225        color: Option<&'static str>,
1226    }
1227
1228    fn edge(
1229        from: usize,
1230        to: usize,
1231        label: &'static str,
1232        style: Style,
1233        color: Option<&'static str>,
1234    ) -> Edge {
1235        Edge {
1236            from: from,
1237            to: to,
1238            label: label,
1239            style: style,
1240            start_arrow: Arrow::default(),
1241            end_arrow: Arrow::default(),
1242            color: color,
1243        }
1244    }
1245
1246    fn edge_with_arrows(
1247        from: usize,
1248        to: usize,
1249        label: &'static str,
1250        style: Style,
1251        start_arrow: Arrow,
1252        end_arrow: Arrow,
1253        color: Option<&'static str>,
1254    ) -> Edge {
1255        Edge {
1256            from: from,
1257            to: to,
1258            label: label,
1259            style: style,
1260            start_arrow: start_arrow,
1261            end_arrow: end_arrow,
1262            color: color,
1263        }
1264    }
1265
1266    struct LabelledGraph {
1267        /// The name for this graph. Used for labelling generated `digraph`.
1268        name: &'static str,
1269
1270        /// Each node is an index into `node_labels`; these labels are
1271        /// used as the label text for each node. (The node *names*,
1272        /// which are unique identifiers, are derived from their index
1273        /// in this array.)
1274        ///
1275        /// If a node maps to None here, then just use its name as its
1276        /// text.
1277        node_labels: Vec<Option<&'static str>>,
1278
1279        node_styles: Vec<Style>,
1280
1281        /// Each edge relates a from-index to a to-index along with a
1282        /// label; `edges` collects them.
1283        edges: Vec<Edge>,
1284    }
1285
1286    // A simple wrapper around LabelledGraph that forces the labels to
1287    // be emitted as EscStr.
1288    struct LabelledGraphWithEscStrs {
1289        graph: LabelledGraph,
1290    }
1291
1292    enum NodeLabels<L> {
1293        AllNodesLabelled(Vec<L>),
1294        UnlabelledNodes(usize),
1295        SomeNodesLabelled(Vec<Option<L>>),
1296    }
1297
1298    type Trivial = NodeLabels<&'static str>;
1299
1300    impl NodeLabels<&'static str> {
1301        fn into_opt_strs(self) -> Vec<Option<&'static str>> {
1302            match self {
1303                UnlabelledNodes(len) => vec![None; len],
1304                AllNodesLabelled(lbls) => lbls.into_iter().map(|l| Some(l)).collect(),
1305                SomeNodesLabelled(lbls) => lbls.into_iter().collect(),
1306            }
1307        }
1308
1309        fn len(&self) -> usize {
1310            match self {
1311                &UnlabelledNodes(len) => len,
1312                &AllNodesLabelled(ref lbls) => lbls.len(),
1313                &SomeNodesLabelled(ref lbls) => lbls.len(),
1314            }
1315        }
1316    }
1317
1318    impl LabelledGraph {
1319        fn new(
1320            name: &'static str,
1321            node_labels: Trivial,
1322            edges: Vec<Edge>,
1323            node_styles: Option<Vec<Style>>,
1324        ) -> LabelledGraph {
1325            let count = node_labels.len();
1326            LabelledGraph {
1327                name: name,
1328                node_labels: node_labels.into_opt_strs(),
1329                edges: edges,
1330                node_styles: match node_styles {
1331                    Some(nodes) => nodes,
1332                    None => vec![Style::None; count],
1333                },
1334            }
1335        }
1336    }
1337
1338    impl LabelledGraphWithEscStrs {
1339        fn new(
1340            name: &'static str,
1341            node_labels: Trivial,
1342            edges: Vec<Edge>,
1343        ) -> LabelledGraphWithEscStrs {
1344            LabelledGraphWithEscStrs {
1345                graph: LabelledGraph::new(name, node_labels, edges, None),
1346            }
1347        }
1348    }
1349
1350    fn id_name<'a>(n: &Node) -> Id<'a> {
1351        Id::new(format!("N{}", *n)).unwrap()
1352    }
1353
1354    impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraph {
1355        fn graph_id(&'a self) -> Id<'a> {
1356            Id::new(&self.name[..]).unwrap()
1357        }
1358        fn node_id(&'a self, n: &Node) -> Id<'a> {
1359            id_name(n)
1360        }
1361        fn node_label(&'a self, n: &Node) -> LabelText<'a> {
1362            match self.node_labels[*n] {
1363                Some(ref l) => LabelStr((*l).into()),
1364                None => LabelStr(id_name(n).name()),
1365            }
1366        }
1367        fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
1368            LabelStr(e.label.into())
1369        }
1370        fn node_style(&'a self, n: &Node) -> Style {
1371            self.node_styles[*n]
1372        }
1373        fn edge_style(&'a self, e: &&'a Edge) -> Style {
1374            e.style
1375        }
1376        fn edge_color(&'a self, e: &&'a Edge) -> Option<LabelText<'a>> {
1377            match e.color {
1378                Some(l) => Some(LabelStr((*l).into())),
1379                None => None,
1380            }
1381        }
1382        fn edge_end_arrow(&'a self, e: &&'a Edge) -> Arrow {
1383            e.end_arrow.clone()
1384        }
1385
1386        fn edge_start_arrow(&'a self, e: &&'a Edge) -> Arrow {
1387            e.start_arrow.clone()
1388        }
1389    }
1390
1391    impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
1392        fn graph_id(&'a self) -> Id<'a> {
1393            self.graph.graph_id()
1394        }
1395        fn node_id(&'a self, n: &Node) -> Id<'a> {
1396            self.graph.node_id(n)
1397        }
1398        fn node_label(&'a self, n: &Node) -> LabelText<'a> {
1399            match self.graph.node_label(n) {
1400                LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
1401            }
1402        }
1403        fn node_color(&'a self, n: &Node) -> Option<LabelText<'a>> {
1404            match self.graph.node_color(n) {
1405                Some(LabelStr(s)) | Some(EscStr(s)) | Some(HtmlStr(s)) => Some(EscStr(s)),
1406                None => None,
1407            }
1408        }
1409        fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
1410            match self.graph.edge_label(e) {
1411                LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
1412            }
1413        }
1414        fn edge_color(&'a self, e: &&'a Edge) -> Option<LabelText<'a>> {
1415            match self.graph.edge_color(e) {
1416                Some(LabelStr(s)) | Some(EscStr(s)) | Some(HtmlStr(s)) => Some(EscStr(s)),
1417                None => None,
1418            }
1419        }
1420    }
1421
1422    impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraph {
1423        fn nodes(&'a self) -> Nodes<'a, Node> {
1424            (0..self.node_labels.len()).collect()
1425        }
1426        fn edges(&'a self) -> Edges<'a, &'a Edge> {
1427            self.edges.iter().collect()
1428        }
1429        fn source(&'a self, edge: &&'a Edge) -> Node {
1430            edge.from
1431        }
1432        fn target(&'a self, edge: &&'a Edge) -> Node {
1433            edge.to
1434        }
1435    }
1436
1437    impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
1438        fn nodes(&'a self) -> Nodes<'a, Node> {
1439            self.graph.nodes()
1440        }
1441        fn edges(&'a self) -> Edges<'a, &'a Edge> {
1442            self.graph.edges()
1443        }
1444        fn source(&'a self, edge: &&'a Edge) -> Node {
1445            edge.from
1446        }
1447        fn target(&'a self, edge: &&'a Edge) -> Node {
1448            edge.to
1449        }
1450    }
1451
1452    fn test_input(g: LabelledGraph) -> io::Result<String> {
1453        let mut writer = Vec::new();
1454        render(&g, &mut writer).unwrap();
1455        let mut s = String::new();
1456        Read::read_to_string(&mut &*writer, &mut s)?;
1457        Ok(s)
1458    }
1459
1460    // All of the tests use raw-strings as the format for the expected outputs,
1461    // so that you can cut-and-paste the content into a .dot file yourself to
1462    // see what the graphviz visualizer would produce.
1463
1464    #[test]
1465    fn empty_graph() {
1466        let labels: Trivial = UnlabelledNodes(0);
1467        let r = test_input(LabelledGraph::new("empty_graph", labels, vec![], None));
1468        assert_eq!(
1469            r.unwrap(),
1470            r#"digraph empty_graph {
1471}
1472"#
1473        );
1474    }
1475
1476    #[test]
1477    fn single_node() {
1478        let labels: Trivial = UnlabelledNodes(1);
1479        let r = test_input(LabelledGraph::new("single_node", labels, vec![], None));
1480        assert_eq!(
1481            r.unwrap(),
1482            r#"digraph single_node {
1483    N0[label="N0"];
1484}
1485"#
1486        );
1487    }
1488
1489    #[test]
1490    fn single_node_with_style() {
1491        let labels: Trivial = UnlabelledNodes(1);
1492        let styles = Some(vec![Style::Dashed]);
1493        let r = test_input(LabelledGraph::new("single_node", labels, vec![], styles));
1494        assert_eq!(
1495            r.unwrap(),
1496            r#"digraph single_node {
1497    N0[label="N0"][style="dashed"];
1498}
1499"#
1500        );
1501    }
1502
1503    #[test]
1504    fn single_edge() {
1505        let labels: Trivial = UnlabelledNodes(2);
1506        let result = test_input(LabelledGraph::new(
1507            "single_edge",
1508            labels,
1509            vec![edge(0, 1, "E", Style::None, None)],
1510            None,
1511        ));
1512        assert_eq!(
1513            result.unwrap(),
1514            r#"digraph single_edge {
1515    N0[label="N0"];
1516    N1[label="N1"];
1517    N0 -> N1[label="E"];
1518}
1519"#
1520        );
1521    }
1522
1523    #[test]
1524    fn single_edge_with_style() {
1525        let labels: Trivial = UnlabelledNodes(2);
1526        let result = test_input(LabelledGraph::new(
1527            "single_edge",
1528            labels,
1529            vec![edge(0, 1, "E", Style::Bold, Some("red"))],
1530            None,
1531        ));
1532        assert_eq!(
1533            result.unwrap(),
1534            r#"digraph single_edge {
1535    N0[label="N0"];
1536    N1[label="N1"];
1537    N0 -> N1[label="E"][style="bold"][color="red"];
1538}
1539"#
1540        );
1541    }
1542
1543    #[test]
1544    fn test_some_labelled() {
1545        let labels: Trivial = SomeNodesLabelled(vec![Some("A"), None]);
1546        let styles = Some(vec![Style::None, Style::Dotted]);
1547        let result = test_input(LabelledGraph::new(
1548            "test_some_labelled",
1549            labels,
1550            vec![edge(0, 1, "A-1", Style::None, None)],
1551            styles,
1552        ));
1553        assert_eq!(
1554            result.unwrap(),
1555            r#"digraph test_some_labelled {
1556    N0[label="A"];
1557    N1[label="N1"][style="dotted"];
1558    N0 -> N1[label="A-1"];
1559}
1560"#
1561        );
1562    }
1563
1564    #[test]
1565    fn single_cyclic_node() {
1566        let labels: Trivial = UnlabelledNodes(1);
1567        let r = test_input(LabelledGraph::new(
1568            "single_cyclic_node",
1569            labels,
1570            vec![edge(0, 0, "E", Style::None, None)],
1571            None,
1572        ));
1573        assert_eq!(
1574            r.unwrap(),
1575            r#"digraph single_cyclic_node {
1576    N0[label="N0"];
1577    N0 -> N0[label="E"];
1578}
1579"#
1580        );
1581    }
1582
1583    #[test]
1584    fn hasse_diagram() {
1585        let labels = AllNodesLabelled(vec!["{x,y}", "{x}", "{y}", "{}"]);
1586        let r = test_input(LabelledGraph::new(
1587            "hasse_diagram",
1588            labels,
1589            vec![
1590                edge(0, 1, "", Style::None, Some("green")),
1591                edge(0, 2, "", Style::None, Some("blue")),
1592                edge(1, 3, "", Style::None, Some("red")),
1593                edge(2, 3, "", Style::None, Some("black")),
1594            ],
1595            None,
1596        ));
1597        assert_eq!(
1598            r.unwrap(),
1599            r#"digraph hasse_diagram {
1600    N0[label="{x,y}"];
1601    N1[label="{x}"];
1602    N2[label="{y}"];
1603    N3[label="{}"];
1604    N0 -> N1[label=""][color="green"];
1605    N0 -> N2[label=""][color="blue"];
1606    N1 -> N3[label=""][color="red"];
1607    N2 -> N3[label=""][color="black"];
1608}
1609"#
1610        );
1611    }
1612
1613    #[test]
1614    fn left_aligned_text() {
1615        let labels = AllNodesLabelled(vec![
1616            "if test {\
1617           \\l    branch1\
1618           \\l} else {\
1619           \\l    branch2\
1620           \\l}\
1621           \\lafterward\
1622           \\l",
1623            "branch1",
1624            "branch2",
1625            "afterward",
1626        ]);
1627
1628        let mut writer = Vec::new();
1629
1630        let g = LabelledGraphWithEscStrs::new(
1631            "syntax_tree",
1632            labels,
1633            vec![
1634                edge(0, 1, "then", Style::None, None),
1635                edge(0, 2, "else", Style::None, None),
1636                edge(1, 3, ";", Style::None, None),
1637                edge(2, 3, ";", Style::None, None),
1638            ],
1639        );
1640
1641        render(&g, &mut writer).unwrap();
1642        let mut r = String::new();
1643        Read::read_to_string(&mut &*writer, &mut r).unwrap();
1644
1645        assert_eq!(
1646            r,
1647            r#"digraph syntax_tree {
1648    N0[label="if test {\l    branch1\l} else {\l    branch2\l}\lafterward\l"];
1649    N1[label="branch1"];
1650    N2[label="branch2"];
1651    N3[label="afterward"];
1652    N0 -> N1[label="then"];
1653    N0 -> N2[label="else"];
1654    N1 -> N3[label=";"];
1655    N2 -> N3[label=";"];
1656}
1657"#
1658        );
1659    }
1660
1661    #[test]
1662    fn simple_id_construction() {
1663        let id1 = Id::new("hello");
1664        match id1 {
1665            Ok(_) => {}
1666            Err(..) => panic!("'hello' is not a valid value for id anymore"),
1667        }
1668    }
1669
1670    #[test]
1671    fn test_some_arrow() {
1672        let labels: Trivial = SomeNodesLabelled(vec![Some("A"), None]);
1673        let styles = Some(vec![Style::None, Style::Dotted]);
1674        let start = Arrow::default();
1675        let end = Arrow::from_arrow(ArrowShape::crow());
1676        let result = test_input(LabelledGraph::new(
1677            "test_some_labelled",
1678            labels,
1679            vec![edge_with_arrows(0, 1, "A-1", Style::None, start, end, None)],
1680            styles,
1681        ));
1682        assert_eq!(
1683            result.unwrap(),
1684            r#"digraph test_some_labelled {
1685    N0[label="A"];
1686    N1[label="N1"][style="dotted"];
1687    N0 -> N1[label="A-1"][arrowhead="crow"];
1688}
1689"#
1690        );
1691    }
1692
1693    #[test]
1694    fn test_some_arrows() {
1695        let labels: Trivial = SomeNodesLabelled(vec![Some("A"), None]);
1696        let styles = Some(vec![Style::None, Style::Dotted]);
1697        let start = Arrow::from_arrow(ArrowShape::tee());
1698        let end = Arrow::from_arrow(ArrowShape::Crow(Side::Left));
1699        let result = test_input(LabelledGraph::new(
1700            "test_some_labelled",
1701            labels,
1702            vec![edge_with_arrows(0, 1, "A-1", Style::None, start, end, None)],
1703            styles,
1704        ));
1705        assert_eq!(
1706            result.unwrap(),
1707            r#"digraph test_some_labelled {
1708    N0[label="A"];
1709    N1[label="N1"][style="dotted"];
1710    N0 -> N1[label="A-1"][arrowhead="lcrow" dir="both" arrowtail="tee"];
1711}
1712"#
1713        );
1714    }
1715
1716    #[test]
1717    fn badly_formatted_id() {
1718        let id2 = Id::new("Weird { struct : ure } !!!");
1719        match id2 {
1720            Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),
1721            Err(..) => {}
1722        }
1723    }
1724
1725    type SimpleEdge = (Node, Node);
1726
1727    struct DefaultStyleGraph {
1728        /// The name for this graph. Used for labelling generated graph
1729        name: &'static str,
1730        nodes: usize,
1731        edges: Vec<SimpleEdge>,
1732        kind: Kind,
1733        rankdir: Option<RankDir>,
1734    }
1735
1736    impl DefaultStyleGraph {
1737        fn new(
1738            name: &'static str,
1739            nodes: usize,
1740            edges: Vec<SimpleEdge>,
1741            kind: Kind,
1742        ) -> DefaultStyleGraph {
1743            assert!(!name.is_empty());
1744            DefaultStyleGraph {
1745                name: name,
1746                nodes: nodes,
1747                edges: edges,
1748                kind: kind,
1749                rankdir: None,
1750            }
1751        }
1752
1753        fn with_rankdir(self, rankdir: Option<RankDir>) -> Self {
1754            Self { rankdir, ..self }
1755        }
1756    }
1757
1758    impl<'a> Labeller<'a, Node, &'a SimpleEdge> for DefaultStyleGraph {
1759        fn graph_id(&'a self) -> Id<'a> {
1760            Id::new(&self.name[..]).unwrap()
1761        }
1762        fn node_id(&'a self, n: &Node) -> Id<'a> {
1763            id_name(n)
1764        }
1765        fn kind(&self) -> Kind {
1766            self.kind
1767        }
1768        fn rank_dir(&self) -> Option<RankDir> {
1769            self.rankdir
1770        }
1771    }
1772
1773    impl<'a> GraphWalk<'a, Node, &'a SimpleEdge> for DefaultStyleGraph {
1774        fn nodes(&'a self) -> Nodes<'a, Node> {
1775            (0..self.nodes).collect()
1776        }
1777        fn edges(&'a self) -> Edges<'a, &'a SimpleEdge> {
1778            self.edges.iter().collect()
1779        }
1780        fn source(&'a self, edge: &&'a SimpleEdge) -> Node {
1781            edge.0
1782        }
1783        fn target(&'a self, edge: &&'a SimpleEdge) -> Node {
1784            edge.1
1785        }
1786    }
1787
1788    fn test_input_default(g: DefaultStyleGraph) -> io::Result<String> {
1789        let mut writer = Vec::new();
1790        render(&g, &mut writer).unwrap();
1791        let mut s = String::new();
1792        Read::read_to_string(&mut &*writer, &mut s)?;
1793        Ok(s)
1794    }
1795
1796    #[test]
1797    fn default_style_graph() {
1798        let r = test_input_default(DefaultStyleGraph::new(
1799            "g",
1800            4,
1801            vec![(0, 1), (0, 2), (1, 3), (2, 3)],
1802            Kind::Graph,
1803        ));
1804        assert_eq!(
1805            r.unwrap(),
1806            r#"graph g {
1807    N0[label="N0"];
1808    N1[label="N1"];
1809    N2[label="N2"];
1810    N3[label="N3"];
1811    N0 -- N1[label=""];
1812    N0 -- N2[label=""];
1813    N1 -- N3[label=""];
1814    N2 -- N3[label=""];
1815}
1816"#
1817        );
1818    }
1819
1820    #[test]
1821    fn default_style_digraph() {
1822        let r = test_input_default(DefaultStyleGraph::new(
1823            "di",
1824            4,
1825            vec![(0, 1), (0, 2), (1, 3), (2, 3)],
1826            Kind::Digraph,
1827        ));
1828        assert_eq!(
1829            r.unwrap(),
1830            r#"digraph di {
1831    N0[label="N0"];
1832    N1[label="N1"];
1833    N2[label="N2"];
1834    N3[label="N3"];
1835    N0 -> N1[label=""];
1836    N0 -> N2[label=""];
1837    N1 -> N3[label=""];
1838    N2 -> N3[label=""];
1839}
1840"#
1841        );
1842    }
1843
1844    #[test]
1845    fn digraph_with_rankdir() {
1846        let r = test_input_default(
1847            DefaultStyleGraph::new("di", 4, vec![(0, 1), (0, 2)], Kind::Digraph)
1848                .with_rankdir(Some(RankDir::LeftRight)),
1849        );
1850        assert_eq!(
1851            r.unwrap(),
1852            r#"digraph di {
1853    rankdir="LR";
1854    N0[label="N0"];
1855    N1[label="N1"];
1856    N2[label="N2"];
1857    N3[label="N3"];
1858    N0 -> N1[label=""];
1859    N0 -> N2[label=""];
1860}
1861"#
1862        );
1863    }
1864}