Skip to main content

MermaidWriter

Struct MermaidWriter 

Source
pub struct MermaidWriter<'a> { /* private fields */ }
Expand description

A writer of Mermaid flowcharts that labels and styles a graph with the caller’s data by node ID and edge index. Mermaid flowcharts render in Markdown.

MermaidWriter::of returns a writer for a graph, the methods that configure it return the writer again, and write or write_to_string write the text. The graph holds no data, so labels, shapes, classes and styles come from hooks that receive a node ID or an edge index and read the caller’s arrays. Here, the packages of a small program get their names from names. The strongly connected components sccs tell which packages are in a cycle, and these are drawn in red:

let mermaid = MermaidWriter::of(&dependencies)
    .node_label(|node| Some(names[node as usize].into()))
    .class_def("cycle", "stroke:red")
    .node_class(|node| {
        sccs.contains_cycle(sccs.scc_of(node))
            .then_some("cycle".into())
    })
    .write_to_string();
// model and storage, the cycle, in red:
//   classDef cycle stroke:red
//   class n4 cycle
//   class n5 cycle

Nodes are named by their node IDs after an n, such as n4. The text lists the class definitions, the clusters in group order with their nodes, then the nodes in no cluster, then the edges in edge index order, the classes of the nodes and the edge styles, so the same graph and hooks always give the same text. Mermaid numbers the edges in the order they are written; the writer translates edge indices into these numbers for linkStyle, also when a filter leaves edges out.

Labels are written as quoted strings: the writer turns quotes, #, %, &, :, <, > and backticks into Mermaid entity codes and line breaks into <br>, so that no label reads as HTML, as a Markdown string or as a directive. For the same reason, whitespace right after the word direction becomes an entity code, and an empty label, which Mermaid rejects, is written as one space. Whitespace there is Java’s: what Character.isWhitespace or Character.isSpaceChar accepts, and U+FEFF - not quite Rust’s char::is_whitespace.

Mermaid’s renderer still changes some labels. Mermaid 11 applies Markdown emphasis and backslash escapes to every label, so 2*3*4 loses its asterisks; Mermaid 12 shows a backslash before n as a line break. Both read ¶ß and fl°, which Mermaid uses internally for entity codes, as ; and &. Both also turn fa:fa-name into an icon in a node label with a line break. With htmlLabels set to false, Mermaid shows some entity codes as written, such as &#58; for :.

Class names must be identifiers - an ASCII letter or underscore, then ASCII letters, digits or underscores - other than a Mermaid keyword: style, linkStyle, interpolate, classDef, class, href, click, call, graph, flowchart, subgraph, end, _self, _blank, _parent and _top. Keywords are case-sensitive, so End is a valid class name. Styles are written as given and must not be blank or contain a line break or a semicolon. Blank means what Java’s String.isBlank accepts.

The text hooks return a Cow: a &str into the caller’s data, which lives for the writer’s lifetime 'a, is written without a copy (Some(names[node as usize].as_str().into())), and a computed text is a String (Some(format!("v{node}").into())). None is Java’s null.

Mermaid renders graphs of a few hundred nodes well; for larger ones, DotWriter in the crate graphity-dot writes DOT (the language of Graphviz). A writer keeps its configuration and can write any number of times. The graph, the partition and the data the hooks read are borrowed for its lifetime 'a. The hooks are Fn closures, called from write through &self.

Since the hooks are arbitrary closures, the writer is neither Send nor Sync - Java’s instances are not safe to share between threads either.

Implementations§

Source§

impl<'a> MermaidWriter<'a>

Source

pub fn of(graph: &'a Graph) -> Self

Returns a writer for graph, top down, with no labels, shapes, classes, clusters or filter yet. The graph of a BiAdjacentGraph is accepted as well, as a &Graph.

Time: O(1).

Source

pub fn direction(self, direction: Direction) -> Self

Sets the direction of the flowchart; without a call, it is Direction::TopDown.

Time: O(1).

Source

pub fn node_label( self, label: impl Fn(u32) -> Option<Cow<'a, str>> + 'a, ) -> Self

Sets the label of each node, by node ID; None shows the name of the node, such as n4. label is called with a node ID and returns the label of the node or None.

Time: O(1).

Source

pub fn edge_label( self, label: impl Fn(u32) -> Option<Cow<'a, str>> + 'a, ) -> Self

Sets the label of each edge, by edge index; None leaves an edge unlabeled. label is called with an edge index and returns the label of the edge or None.

Time: O(1).

Source

pub fn node_shape(self, shape: impl Fn(u32) -> Option<Shape> + 'a) -> Self

Sets the shape of each node, by node ID; None draws a rectangle. shape is called with a node ID and returns the shape of the node or None.

Time: O(1).

Source

pub fn class_def( self, name: impl Into<Cow<'a, str>>, style: impl Into<Cow<'a, str>>, ) -> Self

Defines a class for node_class to assign, written as classDef name style. name is an identifier other than a Mermaid keyword, and style is the style of the class, such as fill:#f96,stroke:#333.

Time: O(number of classes defined + style.len()), as the definitions are a vector of pairs, which for the handful of classes of a chart beats hashing.

§Panics

With an invalid argument message if name is not an identifier or is a Mermaid keyword, or style is blank or contains a line break or a semicolon.

Source

pub fn node_class( self, class_name: impl Fn(u32) -> Option<Cow<'a, str>> + 'a, ) -> Self

Sets the class of each node, by node ID; None assigns none. class_name is called with a node ID and returns the name of the class of the node, an identifier other than a Mermaid keyword, or None.

Time: O(1).

Source

pub fn edge_style( self, style: impl Fn(u32) -> Option<Cow<'a, str>> + 'a, ) -> Self

Sets the style of each edge, by edge index, written as a linkStyle statement; None leaves an edge in the default style. style is called with an edge index and returns the style of the edge, such as stroke:red,stroke-width:2px, or None.

Time: O(1).

Source

pub fn clusters( self, partition: &'a NodePartition, label: impl Fn(u32) -> Option<Cow<'a, str>> + 'a, ) -> Self

Draws each group of partition as a cluster (a Mermaid subgraph), with a label by group ID. label is called with a group ID and returns the label of its cluster or None.

Nodes in no group stay outside every cluster, and a group without a node to write has no cluster. A label of None shows the name of the cluster: c and the group ID, such as c2. An Sccs is accepted as well, as a &NodePartition.

Time: O(1).

§Panics

With an invalid argument message if partition has a different node count than the graph.

Source

pub fn node_filter(self, include: impl Fn(u32) -> bool + 'a) -> Self

Restricts the text to the nodes that include accepts and the edges between them.

Node IDs stay those of the graph, so the hooks keep reading the same arrays.

Time: O(1).

Source

pub fn undirected(self) -> Self

Switches to the undirected reading of the graph: edges without arrowheads.

The edges a -> b and b -> a become one, written as the edge from the lower node ID; the edge hooks receive its edge index.

Time: O(1).

Source

pub fn write<W: Write>(&self, out: W) -> Result<()>

Writes the graph to out, as the text of a Mermaid flowchart.

out is any io::Write, such as a file, standard output, a socket or a Vec<u8>, and receives the text in UTF-8; Java takes an Appendable. It is taken by value: lend it with &mut out to keep using it, and flush it yourself; this call neither flushes nor closes it. Passed by value, it is dropped when the call returns, which closes a File and flushes a BufWriter without reporting an error. The writer issues many small writes, so an unbuffered out such as a File is best wrapped in a BufWriter, lent with &mut and flushed afterwards.

Time: O(node_count + edge_count + group_count), plus the hooks, with group_count the number of groups of the partition drawn as clusters; in the undirected reading, O(log out_degree(target)) more per edge. Memory: the styles of the linkStyle lines while it runs, as they are written last.

§Errors

The first error of out - Java’s IOException.

§Panics

With an invalid argument message if a hook returns a class name that is not an identifier or is a Mermaid keyword, or an edge style that is blank or contains a line break or a semicolon; what was written before stays in out.

Source

pub fn write_to_string(&self) -> String

Returns the text of the Mermaid flowchart, as write writes it.

Time: as for write. Memory: the text for the result, whose buffer may hold up to as much again in spare capacity; while it runs, the linkStyle lines as for write.

§Panics

As for write.

Trait Implementations§

Source§

impl Debug for MermaidWriter<'_>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for MermaidWriter<'a>

§

impl<'a> !Send for MermaidWriter<'a>

§

impl<'a> !Sync for MermaidWriter<'a>

§

impl<'a> !UnwindSafe for MermaidWriter<'a>

§

impl<'a> Freeze for MermaidWriter<'a>

§

impl<'a> Unpin for MermaidWriter<'a>

§

impl<'a> UnsafeUnpin for MermaidWriter<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.