rustc_graphviz/
lib.rs

1//! Generate files suitable for use with [Graphviz](https://www.graphviz.org/)
2//!
3//! The `render` function generates output (e.g., an `output.dot` file) for
4//! use with [Graphviz](https://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](https://www.graphviz.org/docs/outputs), such as SVG.)
8//!
9//! Rather than impose some particular graph data structure on clients,
10//! this library exposes two traits that clients can implement on their
11//! own structs before handing them over to the rendering function.
12//!
13//! Note: This library does not yet provide access to the full
14//! expressiveness of the [DOT language](https://www.graphviz.org/doc/info/lang.html).
15//! For example, there are many [attributes](https://www.graphviz.org/doc/info/attrs.html)
16//! related to providing layout hints (e.g., left-to-right versus top-down, which
17//! algorithm to use, etc). The current intention of this library is to
18//! emit a human-readable .dot file with very regular structure suitable
19//! for easy post-processing.
20//!
21//! # Examples
22//!
23//! The first example uses a very simple graph representation: a list of
24//! pairs of ints, representing the edges (the node set is implicit).
25//! Each node label is derived directly from the int representing the node,
26//! while the edge labels are all empty strings.
27//!
28//! This example also illustrates how to use `Cow<[T]>` to return
29//! an owned vector or a borrowed slice as appropriate: we construct the
30//! node vector from scratch, but borrow the edge list (rather than
31//! constructing a copy of all the edges from scratch).
32//!
33//! The output from this example renders five nodes, with the first four
34//! forming a diamond-shaped acyclic graph and then pointing to the fifth
35//! which is cyclic.
36//!
37//! ```rust
38//! #![feature(rustc_private)]
39//!
40//! use std::io::Write;
41//! use rustc_graphviz as dot;
42//!
43//! type Nd = isize;
44//! type Ed = (isize,isize);
45//! struct Edges(Vec<Ed>);
46//!
47//! pub fn render_to<W: Write>(output: &mut W) {
48//!     let edges = Edges(vec![(0,1), (0,2), (1,3), (2,3), (3,4), (4,4)]);
49//!     dot::render(&edges, output).unwrap()
50//! }
51//!
52//! impl<'a> dot::Labeller<'a> for Edges {
53//!     type Node = Nd;
54//!     type Edge = Ed;
55//!     fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example1").unwrap() }
56//!
57//!     fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
58//!         dot::Id::new(format!("N{}", *n)).unwrap()
59//!     }
60//! }
61//!
62//! impl<'a> dot::GraphWalk<'a> for Edges {
63//!     type Node = Nd;
64//!     type Edge = Ed;
65//!     fn nodes(&self) -> dot::Nodes<'a,Nd> {
66//!         // (assumes that |N| \approxeq |E|)
67//!         let &Edges(ref v) = self;
68//!         let mut nodes = Vec::with_capacity(v.len());
69//!         for &(s,t) in v {
70//!             nodes.push(s); nodes.push(t);
71//!         }
72//!         nodes.sort();
73//!         nodes.dedup();
74//!         nodes.into()
75//!     }
76//!
77//!     fn edges(&'a self) -> dot::Edges<'a,Ed> {
78//!         let &Edges(ref edges) = self;
79//!         (&edges[..]).into()
80//!     }
81//!
82//!     fn source(&self, e: &Ed) -> Nd { let &(s,_) = e; s }
83//!
84//!     fn target(&self, e: &Ed) -> Nd { let &(_,t) = e; t }
85//! }
86//!
87//! # pub fn main() { render_to(&mut Vec::new()) }
88//! ```
89//!
90//! ```no_run
91//! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
92//! pub fn main() {
93//!     use std::fs::File;
94//!     let mut f = File::create("example1.dot").unwrap();
95//!     render_to(&mut f)
96//! }
97//! ```
98//!
99//! Output from first example (in `example1.dot`):
100//!
101//! ```dot
102//! digraph example1 {
103//!     N0[label="N0"];
104//!     N1[label="N1"];
105//!     N2[label="N2"];
106//!     N3[label="N3"];
107//!     N4[label="N4"];
108//!     N0 -> N1[label=""];
109//!     N0 -> N2[label=""];
110//!     N1 -> N3[label=""];
111//!     N2 -> N3[label=""];
112//!     N3 -> N4[label=""];
113//!     N4 -> N4[label=""];
114//! }
115//! ```
116//!
117//! The second example illustrates using `node_label` and `edge_label` to
118//! add labels to the nodes and edges in the rendered graph. The graph
119//! here carries both `nodes` (the label text to use for rendering a
120//! particular node), and `edges` (again a list of `(source,target)`
121//! indices).
122//!
123//! This example also illustrates how to use a type (in this case the edge
124//! type) that shares substructure with the graph: the edge type here is a
125//! direct reference to the `(source,target)` pair stored in the graph's
126//! internal vector (rather than passing around a copy of the pair
127//! itself). Note that this implies that `fn edges(&'a self)` must
128//! construct a fresh `Vec<&'a (usize,usize)>` from the `Vec<(usize,usize)>`
129//! edges stored in `self`.
130//!
131//! Since both the set of nodes and the set of edges are always
132//! constructed from scratch via iterators, we use the `collect()` method
133//! from the `Iterator` trait to collect the nodes and edges into freshly
134//! constructed growable `Vec` values (rather than using `Cow` as in the
135//! first example above).
136//!
137//! The output from this example renders four nodes that make up the
138//! Hasse-diagram for the subsets of the set `{x, y}`. Each edge is
139//! labeled with the &sube; character (specified using the HTML character
140//! entity `&sube`).
141//!
142//! ```rust
143//! #![feature(rustc_private)]
144//!
145//! use std::io::Write;
146//! use rustc_graphviz as dot;
147//!
148//! type Nd = usize;
149//! type Ed<'a> = &'a (usize, usize);
150//! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
151//!
152//! pub fn render_to<W: Write>(output: &mut W) {
153//!     let nodes = vec!["{x,y}","{x}","{y}","{}"];
154//!     let edges = vec![(0,1), (0,2), (1,3), (2,3)];
155//!     let graph = Graph { nodes: nodes, edges: edges };
156//!
157//!     dot::render(&graph, output).unwrap()
158//! }
159//!
160//! impl<'a> dot::Labeller<'a> for Graph {
161//!     type Node = Nd;
162//!     type Edge = Ed<'a>;
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(&self, n: &Nd) -> dot::LabelText<'_> {
168//!         dot::LabelText::LabelStr(self.nodes[*n].into())
169//!     }
170//!     fn edge_label(&self, _: &Ed<'_>) -> dot::LabelText<'_> {
171//!         dot::LabelText::LabelStr("&sube;".into())
172//!     }
173//! }
174//!
175//! impl<'a> dot::GraphWalk<'a> for Graph {
176//!     type Node = Nd;
177//!     type Edge = Ed<'a>;
178//!     fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() }
179//!     fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> { self.edges.iter().collect() }
180//!     fn source(&self, e: &Ed<'_>) -> Nd { let & &(s,_) = e; s }
181//!     fn target(&self, e: &Ed<'_>) -> Nd { let & &(_,t) = e; t }
182//! }
183//!
184//! # pub fn main() { render_to(&mut Vec::new()) }
185//! ```
186//!
187//! ```no_run
188//! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
189//! pub fn main() {
190//!     use std::fs::File;
191//!     let mut f = File::create("example2.dot").unwrap();
192//!     render_to(&mut f)
193//! }
194//! ```
195//!
196//! The third example is similar to the second, except now each node and
197//! edge now carries a reference to the string label for each node as well
198//! as that node's index. (This is another illustration of how to share
199//! structure with the graph itself, and why one might want to do so.)
200//!
201//! The output from this example is the same as the second example: the
202//! Hasse-diagram for the subsets of the set `{x, y}`.
203//!
204//! ```rust
205//! #![feature(rustc_private)]
206//!
207//! use std::io::Write;
208//! use rustc_graphviz as dot;
209//!
210//! type Nd<'a> = (usize, &'a str);
211//! type Ed<'a> = (Nd<'a>, Nd<'a>);
212//! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
213//!
214//! pub fn render_to<W: Write>(output: &mut W) {
215//!     let nodes = vec!["{x,y}","{x}","{y}","{}"];
216//!     let edges = vec![(0,1), (0,2), (1,3), (2,3)];
217//!     let graph = Graph { nodes: nodes, edges: edges };
218//!
219//!     dot::render(&graph, output).unwrap()
220//! }
221//!
222//! impl<'a> dot::Labeller<'a> for Graph {
223//!     type Node = Nd<'a>;
224//!     type Edge = Ed<'a>;
225//!     fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() }
226//!     fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> {
227//!         dot::Id::new(format!("N{}", n.0)).unwrap()
228//!     }
229//!     fn node_label(&self, n: &Nd<'_>) -> dot::LabelText<'_> {
230//!         let &(i, _) = n;
231//!         dot::LabelText::LabelStr(self.nodes[i].into())
232//!     }
233//!     fn edge_label(&self, _: &Ed<'_>) -> dot::LabelText<'_> {
234//!         dot::LabelText::LabelStr("&sube;".into())
235//!     }
236//! }
237//!
238//! impl<'a> dot::GraphWalk<'a> for Graph {
239//!     type Node = Nd<'a>;
240//!     type Edge = Ed<'a>;
241//!     fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
242//!         self.nodes.iter().map(|s| &s[..]).enumerate().collect()
243//!     }
244//!     fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
245//!         self.edges.iter()
246//!             .map(|&(i,j)|((i, &self.nodes[i][..]),
247//!                           (j, &self.nodes[j][..])))
248//!             .collect()
249//!     }
250//!     fn source(&self, e: &Ed<'a>) -> Nd<'a> { let &(s,_) = e; s }
251//!     fn target(&self, e: &Ed<'a>) -> Nd<'a> { let &(_,t) = e; t }
252//! }
253//!
254//! # pub fn main() { render_to(&mut Vec::new()) }
255//! ```
256//!
257//! ```no_run
258//! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
259//! pub fn main() {
260//!     use std::fs::File;
261//!     let mut f = File::create("example3.dot").unwrap();
262//!     render_to(&mut f)
263//! }
264//! ```
265//!
266//! # References
267//!
268//! * [Graphviz](https://www.graphviz.org/)
269//!
270//! * [DOT language](https://www.graphviz.org/doc/info/lang.html)
271
272// tidy-alphabetical-start
273#![doc(test(attr(allow(unused_variables), deny(warnings), allow(internal_features))))]
274// tidy-alphabetical-end
275
276use std::borrow::Cow;
277use std::io;
278use std::io::prelude::*;
279
280use LabelText::*;
281
282/// The text for a graphviz label on a node or edge.
283pub enum LabelText<'a> {
284    /// This kind of label preserves the text directly as is.
285    ///
286    /// Occurrences of backslashes (`\`) are escaped, and thus appear
287    /// as backslashes in the rendered label.
288    LabelStr(Cow<'a, str>),
289
290    /// This kind of label uses the graphviz label escString type:
291    /// <https://www.graphviz.org/docs/attr-types/escString>
292    ///
293    /// Occurrences of backslashes (`\`) are not escaped; instead they
294    /// are interpreted as initiating an escString escape sequence.
295    ///
296    /// Escape sequences of particular interest: in addition to `\n`
297    /// to break a line (centering the line preceding the `\n`), there
298    /// are also the escape sequences `\l` which left-justifies the
299    /// preceding line and `\r` which right-justifies it.
300    EscStr(Cow<'a, str>),
301
302    /// This uses a graphviz [HTML string label][html]. The string is
303    /// printed exactly as given, but between `<` and `>`. **No
304    /// escaping is performed.**
305    ///
306    /// [html]: https://www.graphviz.org/doc/info/shapes.html#html
307    HtmlStr(Cow<'a, str>),
308}
309
310/// The style for a node or edge.
311/// See <https://www.graphviz.org/docs/attr-types/style/> for descriptions.
312/// Note that some of these are not valid for edges.
313#[derive(Copy, Clone, PartialEq, Eq, Debug)]
314pub enum Style {
315    None,
316    Solid,
317    Dashed,
318    Dotted,
319    Bold,
320    Rounded,
321    Diagonals,
322    Filled,
323    Striped,
324    Wedged,
325}
326
327impl Style {
328    pub fn as_slice(self) -> &'static str {
329        match self {
330            Style::None => "",
331            Style::Solid => "solid",
332            Style::Dashed => "dashed",
333            Style::Dotted => "dotted",
334            Style::Bold => "bold",
335            Style::Rounded => "rounded",
336            Style::Diagonals => "diagonals",
337            Style::Filled => "filled",
338            Style::Striped => "striped",
339            Style::Wedged => "wedged",
340        }
341    }
342}
343
344// There is a tension in the design of the labelling API.
345//
346// For example, I considered making a `Labeller<T>` trait that
347// provides labels for `T`, and then making the graph type `G`
348// implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
349// not possible without functional dependencies. (One could work
350// around that, but I did not explore that avenue heavily.)
351//
352// Another approach that I actually used for a while was to make a
353// `Label<Context>` trait that is implemented by the client-specific
354// Node and Edge types (as well as an implementation on Graph itself
355// for the overall name for the graph). The main disadvantage of this
356// second approach (compared to having the `G` type parameter
357// implement a Labelling service) that I have encountered is that it
358// makes it impossible to use types outside of the current crate
359// directly as Nodes/Edges; you need to wrap them in newtype'd
360// structs. See e.g., the `No` and `Ed` structs in the examples. (In
361// practice clients using a graph in some other crate would need to
362// provide some sort of adapter shim over the graph anyway to
363// interface with this library).
364//
365// Another approach would be to make a single `Labeller<N,E>` trait
366// that provides three methods (graph_label, node_label, edge_label),
367// and then make `G` implement `Labeller<N,E>`. At first this did not
368// appeal to me, since I had thought I would need separate methods on
369// each data variant for dot-internal identifiers versus user-visible
370// labels. However, the identifier/label distinction only arises for
371// nodes; graphs themselves only have identifiers, and edges only have
372// labels.
373//
374// So in the end I decided to use the third approach described above.
375
376/// `Id` is a Graphviz `ID`.
377pub struct Id<'a> {
378    name: Cow<'a, str>,
379}
380
381impl<'a> Id<'a> {
382    /// Creates an `Id` named `name`.
383    ///
384    /// The caller must ensure that the input conforms to an
385    /// identifier format: it must be a non-empty string made up of
386    /// alphanumeric or underscore characters, not beginning with a
387    /// digit (i.e., the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
388    ///
389    /// (Note: this format is a strict subset of the `ID` format
390    /// defined by the DOT language. This function may change in the
391    /// future to accept a broader subset, or the entirety, of DOT's
392    /// `ID` format.)
393    ///
394    /// Passing an invalid string (containing spaces, brackets,
395    /// quotes, ...) will return an empty `Err` value.
396    pub fn new<Name: Into<Cow<'a, str>>>(name: Name) -> Result<Id<'a>, ()> {
397        let name = name.into();
398        match name.chars().next() {
399            Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
400            _ => return Err(()),
401        }
402        if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
403            return Err(());
404        }
405
406        Ok(Id { name })
407    }
408
409    pub fn as_slice(&'a self) -> &'a str {
410        &self.name
411    }
412}
413
414/// Each instance of a type that implements `Label<C>` maps to a
415/// unique identifier with respect to `C`, which is used to identify
416/// it in the generated .dot file. They can also provide more
417/// elaborate (and non-unique) label text that is used in the graphviz
418/// rendered output.
419
420/// The graph instance is responsible for providing the DOT compatible
421/// identifiers for the nodes and (optionally) rendered labels for the nodes and
422/// edges, as well as an identifier for the graph itself.
423pub trait Labeller<'a> {
424    type Node;
425    type Edge;
426
427    /// Must return a DOT compatible identifier naming the graph.
428    fn graph_id(&'a self) -> Id<'a>;
429
430    /// Maps `n` to a unique identifier with respect to `self`. The
431    /// implementor is responsible for ensuring that the returned name
432    /// is a valid DOT identifier.
433    fn node_id(&'a self, n: &Self::Node) -> Id<'a>;
434
435    /// Maps `n` to one of the [graphviz `shape` names][1]. If `None`
436    /// is returned, no `shape` attribute is specified.
437    ///
438    /// [1]: https://www.graphviz.org/doc/info/shapes.html
439    fn node_shape(&'a self, _node: &Self::Node) -> Option<LabelText<'a>> {
440        None
441    }
442
443    /// Maps `n` to a label that will be used in the rendered output.
444    /// The label need not be unique, and may be the empty string; the
445    /// default is just the output from `node_id`.
446    fn node_label(&'a self, n: &Self::Node) -> LabelText<'a> {
447        LabelStr(self.node_id(n).name)
448    }
449
450    /// Maps `e` to a label that will be used in the rendered output.
451    /// The label need not be unique, and may be the empty string; the
452    /// default is in fact the empty string.
453    fn edge_label(&'a self, _e: &Self::Edge) -> LabelText<'a> {
454        LabelStr("".into())
455    }
456
457    /// Maps `n` to a style that will be used in the rendered output.
458    fn node_style(&'a self, _n: &Self::Node) -> Style {
459        Style::None
460    }
461
462    /// Maps `e` to a style that will be used in the rendered output.
463    fn edge_style(&'a self, _e: &Self::Edge) -> Style {
464        Style::None
465    }
466}
467
468/// Escape tags in such a way that it is suitable for inclusion in a
469/// Graphviz HTML label.
470pub fn escape_html(s: &str) -> String {
471    s.replace('&', "&amp;")
472        .replace('\"', "&quot;")
473        .replace('<', "&lt;")
474        .replace('>', "&gt;")
475        .replace('\n', "<br align=\"left\"/>")
476}
477
478impl<'a> LabelText<'a> {
479    pub fn label<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
480        LabelStr(s.into())
481    }
482
483    pub fn html<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
484        HtmlStr(s.into())
485    }
486
487    fn escape_char<F>(c: char, mut f: F)
488    where
489        F: FnMut(char),
490    {
491        match c {
492            // not escaping \\, since Graphviz escString needs to
493            // interpret backslashes; see EscStr above.
494            '\\' => f(c),
495            _ => {
496                for c in c.escape_default() {
497                    f(c)
498                }
499            }
500        }
501    }
502    fn escape_str(s: &str) -> String {
503        let mut out = String::with_capacity(s.len());
504        for c in s.chars() {
505            LabelText::escape_char(c, |c| out.push(c));
506        }
507        out
508    }
509
510    /// Renders text as string suitable for a label in a .dot file.
511    /// This includes quotes or suitable delimiters.
512    pub fn to_dot_string(&self) -> String {
513        match *self {
514            LabelStr(ref s) => format!("\"{}\"", s.escape_default()),
515            EscStr(ref s) => format!("\"{}\"", LabelText::escape_str(s)),
516            HtmlStr(ref s) => format!("<{s}>"),
517        }
518    }
519}
520
521pub type Nodes<'a, N> = Cow<'a, [N]>;
522pub type Edges<'a, E> = Cow<'a, [E]>;
523
524// (The type parameters in GraphWalk should be associated items,
525// when/if Rust supports such.)
526
527/// GraphWalk is an abstraction over a directed graph = (nodes,edges)
528/// made up of node handles `N` and edge handles `E`, where each `E`
529/// can be mapped to its source and target nodes.
530///
531/// The lifetime parameter `'a` is exposed in this trait (rather than
532/// introduced as a generic parameter on each method declaration) so
533/// that a client impl can choose `N` and `E` that have substructure
534/// that is bound by the self lifetime `'a`.
535///
536/// The `nodes` and `edges` method each return instantiations of
537/// `Cow<[T]>` to leave implementors the freedom to create
538/// entirely new vectors or to pass back slices into internally owned
539/// vectors.
540pub trait GraphWalk<'a> {
541    type Node: Clone;
542    type Edge: Clone;
543
544    /// Returns all the nodes in this graph.
545    fn nodes(&'a self) -> Nodes<'a, Self::Node>;
546    /// Returns all of the edges in this graph.
547    fn edges(&'a self) -> Edges<'a, Self::Edge>;
548    /// The source node for `edge`.
549    fn source(&'a self, edge: &Self::Edge) -> Self::Node;
550    /// The target node for `edge`.
551    fn target(&'a self, edge: &Self::Edge) -> Self::Node;
552}
553
554#[derive(Clone, PartialEq, Eq, Debug)]
555pub enum RenderOption {
556    NoEdgeLabels,
557    NoNodeLabels,
558    NoEdgeStyles,
559    NoNodeStyles,
560
561    Fontname(String),
562    DarkTheme,
563}
564
565/// Renders directed graph `g` into the writer `w` in DOT syntax.
566/// (Simple wrapper around `render_opts` that passes a default set of options.)
567pub fn render<'a, N, E, G, W>(g: &'a G, w: &mut W) -> io::Result<()>
568where
569    N: Clone + 'a,
570    E: Clone + 'a,
571    G: Labeller<'a, Node = N, Edge = E> + GraphWalk<'a, Node = N, Edge = E>,
572    W: Write,
573{
574    render_opts(g, w, &[])
575}
576
577/// Renders directed graph `g` into the writer `w` in DOT syntax.
578/// (Main entry point for the library.)
579pub fn render_opts<'a, N, E, G, W>(g: &'a G, w: &mut W, options: &[RenderOption]) -> io::Result<()>
580where
581    N: Clone + 'a,
582    E: Clone + 'a,
583    G: Labeller<'a, Node = N, Edge = E> + GraphWalk<'a, Node = N, Edge = E>,
584    W: Write,
585{
586    writeln!(w, "digraph {} {{", g.graph_id().as_slice())?;
587
588    // Global graph properties
589    let mut graph_attrs = Vec::new();
590    let mut content_attrs = Vec::new();
591    let font;
592    if let Some(fontname) = options.iter().find_map(|option| {
593        if let RenderOption::Fontname(fontname) = option { Some(fontname) } else { None }
594    }) {
595        font = format!(r#"fontname="{fontname}""#);
596        graph_attrs.push(&font[..]);
597        content_attrs.push(&font[..]);
598    }
599    if options.contains(&RenderOption::DarkTheme) {
600        graph_attrs.push(r#"bgcolor="black""#);
601        graph_attrs.push(r#"fontcolor="white""#);
602        content_attrs.push(r#"color="white""#);
603        content_attrs.push(r#"fontcolor="white""#);
604    }
605    if !(graph_attrs.is_empty() && content_attrs.is_empty()) {
606        writeln!(w, r#"    graph[{}];"#, graph_attrs.join(" "))?;
607        let content_attrs_str = content_attrs.join(" ");
608        writeln!(w, r#"    node[{content_attrs_str}];"#)?;
609        writeln!(w, r#"    edge[{content_attrs_str}];"#)?;
610    }
611
612    let mut text = Vec::new();
613    for n in g.nodes().iter() {
614        write!(w, "    ")?;
615        let id = g.node_id(n);
616
617        let escaped = &g.node_label(n).to_dot_string();
618
619        write!(text, "{}", id.as_slice()).unwrap();
620
621        if !options.contains(&RenderOption::NoNodeLabels) {
622            write!(text, "[label={escaped}]").unwrap();
623        }
624
625        let style = g.node_style(n);
626        if !options.contains(&RenderOption::NoNodeStyles) && style != Style::None {
627            write!(text, "[style=\"{}\"]", style.as_slice()).unwrap();
628        }
629
630        if let Some(s) = g.node_shape(n) {
631            write!(text, "[shape={}]", &s.to_dot_string()).unwrap();
632        }
633
634        writeln!(text, ";").unwrap();
635        w.write_all(&text)?;
636
637        text.clear();
638    }
639
640    for e in g.edges().iter() {
641        let escaped_label = &g.edge_label(e).to_dot_string();
642        write!(w, "    ")?;
643        let source = g.source(e);
644        let target = g.target(e);
645        let source_id = g.node_id(&source);
646        let target_id = g.node_id(&target);
647
648        write!(text, "{} -> {}", source_id.as_slice(), target_id.as_slice()).unwrap();
649
650        if !options.contains(&RenderOption::NoEdgeLabels) {
651            write!(text, "[label={escaped_label}]").unwrap();
652        }
653
654        let style = g.edge_style(e);
655        if !options.contains(&RenderOption::NoEdgeStyles) && style != Style::None {
656            write!(text, "[style=\"{}\"]", style.as_slice()).unwrap();
657        }
658
659        writeln!(text, ";").unwrap();
660        w.write_all(&text)?;
661
662        text.clear();
663    }
664
665    writeln!(w, "}}")
666}
667
668#[cfg(test)]
669mod tests;