#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/"
)]
use self::LabelText::*;
use std::borrow::Cow;
use std::collections::HashMap;
use std::io;
use std::io::Write;
use std::str;
pub enum LabelText<'a> {
LabelStr(Cow<'a, str>),
EscStr(Cow<'a, str>),
HtmlStr(Cow<'a, str>),
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Style {
None,
Invisible,
Solid,
Dashed,
Dotted,
Bold,
Rounded,
Diagonals,
Filled,
Striped,
Wedged,
}
impl Style {
pub fn as_str(self) -> &'static str {
match self {
Self::None => "",
Self::Invisible => "invis",
Self::Solid => "solid",
Self::Dashed => "dashed",
Self::Dotted => "dotted",
Self::Bold => "bold",
Self::Rounded => "rounded",
Self::Diagonals => "diagonals",
Self::Filled => "filled",
Self::Striped => "striped",
Self::Wedged => "wedged",
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum RankDir {
TopBottom,
LeftRight,
BottomTop,
RightLeft,
}
impl RankDir {
pub fn as_str(self) -> &'static str {
match self {
Self::TopBottom => "TB",
Self::LeftRight => "LR",
Self::BottomTop => "BT",
Self::RightLeft => "RL",
}
}
}
pub struct Id<'a> {
name: Cow<'a, str>,
}
impl<'a> Id<'a> {
pub fn new<Name: Into<Cow<'a, str>>>(name: Name) -> Result<Self, &'static str> {
let name = name.into();
{
let mut chars = name.chars();
match chars.next() {
Some(c) if is_letter_or_underscore(c) => {}
_ => return Err("First character is not a letter or an underscore"),
}
if !chars.all(is_constituent) {
return Err("Contains characters which are not alphanumeric/underscore characters");
}
}
return Ok(Id { name });
fn is_letter_or_underscore(c: char) -> bool {
c.is_ascii_alphabetic() || c == '_'
}
fn is_constituent(c: char) -> bool {
is_letter_or_underscore(c) || c.is_ascii_digit()
}
}
pub fn as_str(&'a self) -> &'a str {
&self.name
}
pub fn name(self) -> Cow<'a, str> {
self.name
}
}
pub trait Labeller<'a, N, E, S = ()> {
fn graph_id(&'a self) -> Id<'a>;
fn graph_attrs(&'a self) -> HashMap<&'a str, &'a str> {
HashMap::default()
}
fn node_id(&'a self, n: &N) -> Id<'a>;
fn node_shape(&'a self, _node: &N) -> Option<LabelText<'a>> {
None
}
fn node_label(&'a self, n: &N) -> LabelText<'a> {
LabelStr(self.node_id(n).name())
}
fn edge_label(&'a self, e: &E) -> LabelText<'a> {
let _ignored = e;
LabelStr("".into())
}
fn node_style(&'a self, _n: &N) -> Style {
Style::None
}
fn rank_dir(&'a self) -> Option<RankDir> {
None
}
fn node_color(&'a self, _node: &N) -> Option<LabelText<'a>> {
None
}
fn node_attrs(&'a self, _n: &N) -> HashMap<&'a str, &'a str> {
HashMap::default()
}
fn edge_end_arrow(&'a self, _e: &E) -> Arrow {
Arrow::default()
}
fn edge_start_arrow(&'a self, _e: &E) -> Arrow {
Arrow::default()
}
fn edge_style(&'a self, _e: &E) -> Style {
Style::None
}
fn edge_color(&'a self, _e: &E) -> Option<LabelText<'a>> {
None
}
fn edge_attrs(&'a self, _e: &E) -> HashMap<&'a str, &'a str> {
HashMap::default()
}
#[inline]
fn kind(&self) -> Kind {
Kind::Digraph
}
fn subgraph_id(&'a self, _s: &S) -> Option<Id<'a>> {
None
}
fn subgraph_label(&'a self, _s: &S) -> LabelText<'a> {
LabelStr("".into())
}
fn subgraph_style(&'a self, _s: &S) -> Style {
Style::None
}
fn subgraph_shape(&'a self, _s: &S) -> Option<LabelText<'a>> {
None
}
fn subgraph_color(&'a self, _s: &S) -> Option<LabelText<'a>> {
None
}
fn source_port_position(&'a self, _e: &E) -> (Option<Id<'a>>, Option<CompassPoint>) {
(None, None)
}
fn target_port_position(&'a self, _e: &E) -> (Option<Id<'a>>, Option<CompassPoint>) {
(None, None)
}
}
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum CompassPoint {
N,
NE,
E,
SE,
S,
SW,
W,
NW,
C,
Underscore,
}
impl CompassPoint {
fn as_str(self) -> &'static str {
use CompassPoint::*;
match self {
N => "n",
NE => "ne",
E => "e",
SE => "se",
S => "s",
SW => "sw",
W => "w",
NW => "nw",
C => "c",
Underscore => "_",
}
}
}
pub fn escape_html(s: &str) -> String {
s.replace('&', "&")
.replace('\"', """)
.replace('<', "<")
.replace('>', ">")
}
impl<'a> LabelText<'a> {
pub fn label<S: Into<Cow<'a, str>>>(s: S) -> Self {
LabelStr(s.into())
}
pub fn escaped<S: Into<Cow<'a, str>>>(s: S) -> Self {
EscStr(s.into())
}
pub fn html<S: Into<Cow<'a, str>>>(s: S) -> Self {
HtmlStr(s.into())
}
fn escape_ascii_char(c: char) -> String {
if c.is_ascii() || c.is_control() || c.is_whitespace() {
c.escape_default().to_string()
} else {
String::from(c)
}
}
fn escape_char<F>(c: char, mut f: F)
where
F: FnMut(char),
{
match c {
'\\' => f(c),
_ => {
for c in c.escape_default() {
f(c)
}
}
}
}
fn escape_str(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
LabelText::escape_char(c, |c| out.push(c));
}
out
}
fn escape_default(s: &str) -> String {
let mut buf = String::new();
for c in s.chars() {
buf.push_str(Self::escape_ascii_char(c).as_str());
}
buf
}
pub fn to_dot_string(&self) -> String {
match self {
LabelStr(s) => format!("\"{}\"", LabelText::escape_default(s)),
EscStr(s) => format!("\"{}\"", LabelText::escape_str(&s[..])),
HtmlStr(s) => format!("<{}>", s),
}
}
fn pre_escaped_content(self) -> Cow<'a, str> {
match self {
EscStr(s) => s,
LabelStr(s) => {
if s.contains('\\') {
LabelText::escape_default(&s).into()
} else {
s
}
}
HtmlStr(s) => s,
}
}
pub fn prefix_line(self, prefix: LabelText) -> LabelText<'static> {
prefix.suffix_line(self)
}
pub fn suffix_line(self, suffix: LabelText) -> LabelText<'static> {
let mut prefix = self.pre_escaped_content().into_owned();
let suffix = suffix.pre_escaped_content();
prefix.push_str(r"\n\n");
prefix.push_str(&suffix[..]);
EscStr(prefix.into())
}
}
#[derive(Clone, Default, Hash, PartialEq, Eq)]
pub struct Arrow {
pub arrows: Vec<ArrowShape>,
}
use self::ArrowShape::*;
impl Arrow {
fn is_default(&self) -> bool {
self.arrows.is_empty()
}
pub fn none() -> Self {
Self {
arrows: vec![NoArrow],
}
}
pub fn normal() -> Self {
Self {
arrows: vec![ArrowShape::normal()],
}
}
pub fn from_arrow(arrow: ArrowShape) -> Self {
Self {
arrows: vec![arrow],
}
}
pub fn to_dot_string(&self) -> String {
let mut cow = String::new();
for arrow in &self.arrows {
cow.push_str(&arrow.to_dot_string());
}
cow
}
}
impl From<[ArrowShape; 2]> for Arrow {
fn from(val: [ArrowShape; 2]) -> Self {
Self {
arrows: vec![val[0], val[1]],
}
}
}
impl From<[ArrowShape; 3]> for Arrow {
fn from(val: [ArrowShape; 3]) -> Self {
Self {
arrows: vec![val[0], val[1], val[2]],
}
}
}
impl From<[ArrowShape; 4]> for Arrow {
fn from(val: [ArrowShape; 4]) -> Self {
Self {
arrows: vec![val[0], val[1], val[2], val[3]],
}
}
}
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub enum Fill {
Open,
Filled,
}
impl Fill {
pub fn as_str(self) -> &'static str {
match self {
Self::Open => "o",
Self::Filled => "",
}
}
}
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub enum Side {
Left,
Right,
Both,
}
impl Side {
pub fn as_str(self) -> &'static str {
match self {
Self::Left => "l",
Self::Right => "r",
Self::Both => "",
}
}
}
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub enum ArrowShape {
NoArrow,
Normal(Fill, Side),
Box(Fill, Side),
Crow(Side),
Curve(Side),
ICurve(Fill, Side),
Diamond(Fill, Side),
Dot(Fill),
Inv(Fill, Side),
Tee(Side),
Vee(Side),
}
impl ArrowShape {
pub fn none() -> Self {
NoArrow
}
pub fn normal() -> Self {
Normal(Fill::Filled, Side::Both)
}
pub fn boxed() -> Self {
Box(Fill::Filled, Side::Both)
}
pub fn crow() -> Self {
Crow(Side::Both)
}
pub fn curve() -> Self {
Curve(Side::Both)
}
pub fn icurve() -> Self {
ICurve(Fill::Filled, Side::Both)
}
pub fn diamond() -> Self {
Diamond(Fill::Filled, Side::Both)
}
pub fn dot() -> Self {
Diamond(Fill::Filled, Side::Both)
}
pub fn inv() -> Self {
Inv(Fill::Filled, Side::Both)
}
pub fn tee() -> Self {
Tee(Side::Both)
}
pub fn vee() -> Self {
Vee(Side::Both)
}
pub fn to_dot_string(&self) -> String {
let mut res = String::new();
match self {
Box(fill, side)
| ICurve(fill, side)
| Diamond(fill, side)
| Inv(fill, side)
| Normal(fill, side) => {
res.push_str(fill.as_str());
if matches!(side, Side::Left | Side::Right) {
res.push_str(side.as_str());
}
}
Dot(fill) => res.push_str(fill.as_str()),
Crow(side) | Curve(side) | Tee(side) | Vee(side) => {
if matches!(side, Side::Left | Side::Right) {
res.push_str(side.as_str());
}
}
NoArrow => {}
};
res.push_str(match self {
NoArrow => "none",
Normal(_, _) => "normal",
Box(_, _) => "box",
Crow(_) => "crow",
Curve(_) => "curve",
ICurve(_, _) => "icurve",
Diamond(_, _) => "diamond",
Dot(_) => "dot",
Inv(_, _) => "inv",
Tee(_) => "tee",
Vee(_) => "vee",
});
res
}
}
pub type Subgraphs<'a, S> = Cow<'a, [S]>;
pub type Nodes<'a, N> = Cow<'a, [N]>;
pub type Edges<'a, E> = Cow<'a, [E]>;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Kind {
Digraph,
Graph,
}
impl Kind {
fn keyword(&self) -> &'static str {
match self {
Self::Digraph => "digraph",
Self::Graph => "graph",
}
}
fn edgeop(&self) -> &'static str {
match self {
Self::Digraph => "->",
Self::Graph => "--",
}
}
}
pub trait GraphWalk<'a, N: Clone, E: Clone, S: Clone = ()> {
fn nodes(&'a self) -> Nodes<'a, N>;
fn edges(&'a self) -> Edges<'a, E>;
fn source(&'a self, edge: &E) -> N;
fn target(&'a self, edge: &E) -> N;
fn subgraphs(&'a self) -> Subgraphs<'a, S> {
std::borrow::Cow::Borrowed(&[])
}
fn subgraph_nodes(&'a self, _s: &S) -> Nodes<'a, N> {
std::borrow::Cow::Borrowed(&[])
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum RenderOption {
NoEdgeLabels,
NoNodeLabels,
NoEdgeStyles,
NoEdgeColors,
NoNodeStyles,
NoNodeColors,
NoArrows,
}
pub fn default_options() -> Vec<RenderOption> {
vec![]
}
pub fn render<
'a,
N: Clone + 'a,
E: Clone + 'a,
S: Clone + 'a,
G: Labeller<'a, N, E, S> + GraphWalk<'a, N, E, S>,
W: Write,
>(
g: &'a G,
w: &mut W,
) -> io::Result<()> {
render_opts(g, w, &[])
}
pub fn render_opts<
'a,
N: Clone + 'a,
E: Clone + 'a,
S: Clone + 'a,
G: Labeller<'a, N, E, S> + GraphWalk<'a, N, E, S>,
W: Write,
>(
g: &'a G,
w: &mut W,
options: &[RenderOption],
) -> io::Result<()> {
writeln(w, &[g.kind().keyword(), " ", g.graph_id().as_str(), " {"])?;
render_subgraphs(g, w, options)?;
if g.kind() == Kind::Digraph
&& let Some(rankdir) = g.rank_dir()
{
indent(w)?;
writeln(w, &["rankdir=\"", rankdir.as_str(), "\";"])?;
}
for (name, value) in g.graph_attrs().iter() {
writeln(w, &[name, "=", value])?;
}
render_nodes(g, w, options)?;
render_edges(g, w, options)?;
writeln(w, &["}"])
}
fn writeln<W: Write>(w: &mut W, arg: &[&str]) -> io::Result<()> {
for &s in arg {
w.write_all(s.as_bytes())?;
}
writeln!(w)
}
fn indent<W: Write>(w: &mut W) -> io::Result<()> {
w.write_all(b" ")
}
fn render_subgraphs<
'a,
N: Clone + 'a,
E: Clone + 'a,
S: Clone + 'a,
G: Labeller<'a, N, E, S> + GraphWalk<'a, N, E, S>,
W: Write,
>(
g: &'a G,
w: &mut W,
options: &[RenderOption],
) -> io::Result<()> {
for s in g.subgraphs().iter() {
let label;
let colorstring;
let shape;
let mut text = vec!["subgraph "];
let id = g
.subgraph_id(s)
.map(|x| format!("{} ", x.name()))
.unwrap_or_default();
text.push(&id);
text.push("{\n");
if !options.contains(&RenderOption::NoNodeLabels) {
label = format!("label={};\n", g.subgraph_label(s).to_dot_string());
text.push(&label);
}
let style = g.subgraph_style(s);
if !options.contains(&RenderOption::NoNodeStyles) && style != Style::None {
text.push("style=\"");
text.push(style.as_str());
text.push("\";\n");
}
let color = g.subgraph_color(s);
if !options.contains(&RenderOption::NoNodeColors)
&& let Some(c) = color
{
colorstring = c.to_dot_string();
text.push("color=");
text.push(&colorstring);
text.push(";\n");
}
if let Some(s) = g.subgraph_shape(s) {
shape = s.to_dot_string();
text.push("shape=\"");
text.push(&shape);
text.push(";\n");
}
writeln(w, &text)?;
for n in g.subgraph_nodes(s).iter() {
writeln(w, &[g.node_id(n).as_str(), ";"])?;
}
writeln(w, &["\n}\n"])?;
}
Ok(())
}
fn render_nodes<
'a,
N: Clone + 'a,
E: Clone + 'a,
S: Clone + 'a,
G: Labeller<'a, N, E, S> + GraphWalk<'a, N, E, S>,
W: Write,
>(
g: &'a G,
w: &mut W,
options: &[RenderOption],
) -> io::Result<()> {
for n in g.nodes().iter() {
let colorstring;
indent(w)?;
let id = g.node_id(n);
let escaped = &g.node_label(n).to_dot_string();
let shape;
let mut text = vec![id.as_str()];
if !options.contains(&RenderOption::NoNodeLabels) {
text.push("[label=");
text.push(escaped);
text.push("]");
}
let style = g.node_style(n);
if !options.contains(&RenderOption::NoNodeStyles) && style != Style::None {
text.push("[style=\"");
text.push(style.as_str());
text.push("\"]");
}
let color = g.node_color(n);
if !options.contains(&RenderOption::NoNodeColors)
&& let Some(c) = color
{
colorstring = c.to_dot_string();
text.push("[color=");
text.push(&colorstring);
text.push("]");
}
if let Some(s) = g.node_shape(n) {
shape = s.to_dot_string();
text.push("[shape=");
text.push(&shape);
text.push("]");
}
let node_attrs = g
.node_attrs(n)
.iter()
.map(|(name, value)| format!("[{name}={value}]"))
.collect::<Vec<String>>();
text.extend(node_attrs.iter().map(|s| s.as_str()));
text.push(";");
writeln(w, &text)?;
}
Ok(())
}
fn render_edges<
'a,
N: Clone + 'a,
E: Clone + 'a,
S: Clone + 'a,
G: Labeller<'a, N, E, S> + GraphWalk<'a, N, E, S>,
W: Write,
>(
g: &'a G,
w: &mut W,
options: &[RenderOption],
) -> io::Result<()> {
for e in g.edges().iter() {
let colorstring;
let escaped_label = &g.edge_label(e).to_dot_string();
let start_arrow = g.edge_start_arrow(e);
let end_arrow = g.edge_end_arrow(e);
let start_arrow_s = start_arrow.to_dot_string();
let end_arrow_s = end_arrow.to_dot_string();
indent(w)?;
let source = g.source(e);
let target = g.target(e);
let source_id = g.node_id(&source);
let target_id = g.node_id(&target);
let mut text = vec![source_id.as_str()];
let (source_port, source_direction) = g.source_port_position(e);
if let Some(ref refinement) = source_port {
text.push(":");
text.push(refinement.as_str());
}
if let Some(dir) = source_direction {
text.push(":");
text.push(dir.as_str());
}
text.extend(&[" ", g.kind().edgeop(), " ", target_id.as_str()]);
let (target_port, target_direction) = g.target_port_position(e);
if let Some(ref refinement) = target_port {
text.push(":");
text.push(refinement.as_str());
}
if let Some(dir) = target_direction {
text.push(":");
text.push(dir.as_str());
}
if !options.contains(&RenderOption::NoEdgeLabels) {
text.push("[label=");
text.push(escaped_label);
text.push("]");
}
let style = g.edge_style(e);
if !options.contains(&RenderOption::NoEdgeStyles) && style != Style::None {
text.push("[style=\"");
text.push(style.as_str());
text.push("\"]");
}
let color = g.edge_color(e);
if !options.contains(&RenderOption::NoEdgeColors)
&& let Some(c) = color
{
colorstring = c.to_dot_string();
text.push("[color=");
text.push(&colorstring);
text.push("]");
}
if !options.contains(&RenderOption::NoArrows)
&& (!start_arrow.is_default() || !end_arrow.is_default())
{
text.push("[");
if !end_arrow.is_default() {
text.push("arrowhead=\"");
text.push(&end_arrow_s);
text.push("\"");
}
if !start_arrow.is_default() {
text.push(" dir=\"both\" arrowtail=\"");
text.push(&start_arrow_s);
text.push("\"");
}
text.push("]");
}
let edge_attrs = g
.edge_attrs(e)
.iter()
.map(|(name, value)| format!("[{name}={value}]"))
.collect::<Vec<String>>();
text.extend(edge_attrs.iter().map(|s| s.as_str()));
text.push(";");
writeln(w, &text)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use self::NodeLabels::*;
use super::LabelText::{self, EscStr, HtmlStr, LabelStr};
use super::{Arrow, ArrowShape, Side};
use super::{Edges, GraphWalk, Id, Kind, Labeller, Nodes, RankDir, Style, Subgraphs, render};
use expect_test::{Expect, expect};
type Node = usize;
struct Edge {
from: usize,
to: usize,
label: &'static str,
style: Style,
start_arrow: Arrow,
end_arrow: Arrow,
color: Option<&'static str>,
}
fn edge(
from: usize,
to: usize,
label: &'static str,
style: Style,
color: Option<&'static str>,
) -> Edge {
Edge {
from,
to,
label,
style,
start_arrow: Arrow::default(),
end_arrow: Arrow::default(),
color,
}
}
fn edge_with_arrows(
from: usize,
to: usize,
label: &'static str,
style: Style,
start_arrow: Arrow,
end_arrow: Arrow,
color: Option<&'static str>,
) -> Edge {
Edge {
from,
to,
label,
style,
start_arrow,
end_arrow,
color,
}
}
struct LabelledGraph {
name: &'static str,
node_labels: Vec<Option<&'static str>>,
node_styles: Vec<Style>,
edges: Vec<Edge>,
}
struct LabelledGraphWithEscStrs {
graph: LabelledGraph,
}
enum NodeLabels<L> {
AllNodesLabelled(Vec<L>),
UnlabelledNodes(usize),
SomeNodesLabelled(Vec<Option<L>>),
}
type Trivial = NodeLabels<&'static str>;
impl NodeLabels<&'static str> {
fn into_opt_strs(self) -> Vec<Option<&'static str>> {
match self {
UnlabelledNodes(len) => vec![None; len],
AllNodesLabelled(lbls) => lbls.into_iter().map(Some).collect(),
SomeNodesLabelled(lbls) => lbls.into_iter().collect(),
}
}
fn len(&self) -> usize {
match self {
&UnlabelledNodes(len) => len,
AllNodesLabelled(lbls) => lbls.len(),
SomeNodesLabelled(lbls) => lbls.len(),
}
}
}
impl LabelledGraph {
fn new(
name: &'static str,
node_labels: Trivial,
edges: Vec<Edge>,
node_styles: Option<Vec<Style>>,
) -> Self {
let count = node_labels.len();
Self {
name,
node_labels: node_labels.into_opt_strs(),
edges,
node_styles: match node_styles {
Some(nodes) => nodes,
None => vec![Style::None; count],
},
}
}
}
impl LabelledGraphWithEscStrs {
fn new(name: &'static str, node_labels: Trivial, edges: Vec<Edge>) -> Self {
Self {
graph: LabelledGraph::new(name, node_labels, edges, None),
}
}
}
fn id_name<'a>(n: &Node) -> Id<'a> {
Id::new(format!("N{}", *n)).unwrap()
}
impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraph {
fn graph_id(&'a self) -> Id<'a> {
Id::new(self.name).unwrap()
}
fn node_id(&'a self, n: &Node) -> Id<'a> {
id_name(n)
}
fn node_label(&'a self, n: &Node) -> LabelText<'a> {
match self.node_labels[*n] {
Some(l) => LabelStr(l.into()),
None => LabelStr(id_name(n).name()),
}
}
fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
LabelStr(e.label.into())
}
fn node_style(&'a self, n: &Node) -> Style {
self.node_styles[*n]
}
fn edge_style(&'a self, e: &&'a Edge) -> Style {
e.style
}
fn edge_color(&'a self, e: &&'a Edge) -> Option<LabelText<'a>> {
e.color.map(|l| LabelStr((*l).into()))
}
fn edge_end_arrow(&'a self, e: &&'a Edge) -> Arrow {
e.end_arrow.clone()
}
fn edge_start_arrow(&'a self, e: &&'a Edge) -> Arrow {
e.start_arrow.clone()
}
}
impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
fn graph_id(&'a self) -> Id<'a> {
self.graph.graph_id()
}
fn node_id(&'a self, n: &Node) -> Id<'a> {
self.graph.node_id(n)
}
fn node_label(&'a self, n: &Node) -> LabelText<'a> {
match self.graph.node_label(n) {
LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
}
}
fn node_color(&'a self, n: &Node) -> Option<LabelText<'a>> {
match self.graph.node_color(n) {
Some(LabelStr(s) | EscStr(s) | HtmlStr(s)) => Some(EscStr(s)),
None => None,
}
}
fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
match self.graph.edge_label(e) {
LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
}
}
fn edge_color(&'a self, e: &&'a Edge) -> Option<LabelText<'a>> {
match self.graph.edge_color(e) {
Some(LabelStr(s) | EscStr(s) | HtmlStr(s)) => Some(EscStr(s)),
None => None,
}
}
}
impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraph {
fn nodes(&'a self) -> Nodes<'a, Node> {
(0..self.node_labels.len()).collect()
}
fn edges(&'a self) -> Edges<'a, &'a Edge> {
self.edges.iter().collect()
}
fn source(&'a self, edge: &&'a Edge) -> Node {
edge.from
}
fn target(&'a self, edge: &&'a Edge) -> Node {
edge.to
}
}
impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
fn nodes(&'a self) -> Nodes<'a, Node> {
self.graph.nodes()
}
fn edges(&'a self) -> Edges<'a, &'a Edge> {
self.graph.edges()
}
fn source(&'a self, edge: &&'a Edge) -> Node {
edge.from
}
fn target(&'a self, edge: &&'a Edge) -> Node {
edge.to
}
}
fn check_input<
'a,
N: Clone + 'a,
E: Clone + 'a,
S: Clone + 'a,
G: Labeller<'a, N, E, S> + GraphWalk<'a, N, E, S>,
>(
g: &'a G,
expect: Expect,
) {
let mut data = Vec::new();
render(g, &mut data).unwrap();
expect.assert_eq(str::from_utf8(&data).unwrap());
}
#[test]
fn empty_graph() {
let labels: Trivial = UnlabelledNodes(0);
check_input(
&LabelledGraph::new("empty_graph", labels, vec![], None),
expect![[r#"digraph empty_graph {
}
"#]],
);
}
#[test]
fn single_node() {
let labels: Trivial = UnlabelledNodes(1);
check_input(
&LabelledGraph::new("single_node", labels, vec![], None),
expect![[r#"digraph single_node {
N0[label="N0"];
}
"#]],
);
}
#[test]
fn single_node_with_style() {
let labels: Trivial = UnlabelledNodes(1);
let styles = Some(vec![Style::Dashed]);
check_input(
&LabelledGraph::new("single_node", labels, vec![], styles),
expect![[r#"digraph single_node {
N0[label="N0"][style="dashed"];
}
"#]],
);
}
#[test]
fn single_edge() {
let labels: Trivial = UnlabelledNodes(2);
check_input(
&LabelledGraph::new(
"single_edge",
labels,
vec![edge(0, 1, "E", Style::None, None)],
None,
),
expect![[r#"digraph single_edge {
N0[label="N0"];
N1[label="N1"];
N0 -> N1[label="E"];
}
"#]],
);
}
#[test]
fn single_edge_with_style() {
let labels: Trivial = UnlabelledNodes(2);
check_input(
&LabelledGraph::new(
"single_edge",
labels,
vec![edge(0, 1, "E", Style::Bold, Some("red"))],
None,
),
expect![[r#"digraph single_edge {
N0[label="N0"];
N1[label="N1"];
N0 -> N1[label="E"][style="bold"][color="red"];
}
"#]],
);
}
#[test]
fn test_some_labelled() {
let labels: Trivial = SomeNodesLabelled(vec![Some("A"), None]);
let styles = Some(vec![Style::None, Style::Dotted]);
check_input(
&LabelledGraph::new(
"test_some_labelled",
labels,
vec![edge(0, 1, "A-1", Style::None, None)],
styles,
),
expect![[r#"digraph test_some_labelled {
N0[label="A"];
N1[label="N1"][style="dotted"];
N0 -> N1[label="A-1"];
}
"#]],
);
}
#[test]
fn single_cyclic_node() {
let labels: Trivial = UnlabelledNodes(1);
check_input(
&LabelledGraph::new(
"single_cyclic_node",
labels,
vec![edge(0, 0, "E", Style::None, None)],
None,
),
expect![[r#"digraph single_cyclic_node {
N0[label="N0"];
N0 -> N0[label="E"];
}
"#]],
);
}
#[test]
fn invisible() {
let labels: Trivial = UnlabelledNodes(1);
check_input(
&LabelledGraph::new(
"single_cyclic_node",
labels,
vec![edge(0, 0, "E", Style::Invisible, None)],
Some(vec![Style::Invisible]),
),
expect![[r#"digraph single_cyclic_node {
N0[label="N0"][style="invis"];
N0 -> N0[label="E"][style="invis"];
}
"#]],
);
}
#[test]
fn hasse_diagram() {
let labels = AllNodesLabelled(vec!["{x,y}", "{x}", "{y}", "{}"]);
check_input(
&LabelledGraph::new(
"hasse_diagram",
labels,
vec![
edge(0, 1, "", Style::None, Some("green")),
edge(0, 2, "", Style::None, Some("blue")),
edge(1, 3, "", Style::None, Some("red")),
edge(2, 3, "", Style::None, Some("black")),
],
None,
),
expect![[r#"digraph hasse_diagram {
N0[label="{x,y}"];
N1[label="{x}"];
N2[label="{y}"];
N3[label="{}"];
N0 -> N1[label=""][color="green"];
N0 -> N2[label=""][color="blue"];
N1 -> N3[label=""][color="red"];
N2 -> N3[label=""][color="black"];
}
"#]],
);
}
#[test]
fn utf8_diagram() {
let labels = AllNodesLabelled(vec!["Λ", "ι"]);
check_input(
&LabelledGraph::new(
"utf8_diagram",
labels,
vec![edge(0, 1, "☕", Style::None, None)],
None,
),
expect![[r#"digraph utf8_diagram {
N0[label="Λ"];
N1[label="ι"];
N0 -> N1[label="☕"];
}
"#]],
);
}
#[test]
fn left_aligned_text() {
let labels = AllNodesLabelled(vec![
"if test {\
\\l branch1\
\\l} else {\
\\l branch2\
\\l}\
\\lafterward\
\\l",
"branch1",
"branch2",
"afterward",
]);
check_input(
&LabelledGraphWithEscStrs::new(
"syntax_tree",
labels,
vec![
edge(0, 1, "then", Style::None, None),
edge(0, 2, "else", Style::None, None),
edge(1, 3, ";", Style::None, None),
edge(2, 3, ";", Style::None, None),
],
),
expect![[r#"digraph syntax_tree {
N0[label="if test {\l branch1\l} else {\l branch2\l}\lafterward\l"];
N1[label="branch1"];
N2[label="branch2"];
N3[label="afterward"];
N0 -> N1[label="then"];
N0 -> N2[label="else"];
N1 -> N3[label=";"];
N2 -> N3[label=";"];
}
"#]],
);
}
#[test]
fn simple_id_construction() {
let id1 = Id::new("hello");
assert!(id1.is_ok(), "'hello' is not a valid value for id anymore");
}
#[test]
fn test_some_arrow() {
let labels: Trivial = SomeNodesLabelled(vec![Some("A"), None]);
let styles = Some(vec![Style::None, Style::Dotted]);
let start = Arrow::default();
let end = Arrow::from_arrow(ArrowShape::crow());
check_input(
&LabelledGraph::new(
"test_some_labelled",
labels,
vec![edge_with_arrows(0, 1, "A-1", Style::None, start, end, None)],
styles,
),
expect![[r#"digraph test_some_labelled {
N0[label="A"];
N1[label="N1"][style="dotted"];
N0 -> N1[label="A-1"][arrowhead="crow"];
}
"#]],
);
}
#[test]
fn test_some_arrows() {
let labels: Trivial = SomeNodesLabelled(vec![Some("A"), None]);
let styles = Some(vec![Style::None, Style::Dotted]);
let start = Arrow::from_arrow(ArrowShape::tee());
let end = Arrow::from_arrow(ArrowShape::Crow(Side::Left));
check_input(
&LabelledGraph::new(
"test_some_labelled",
labels,
vec![edge_with_arrows(0, 1, "A-1", Style::None, start, end, None)],
styles,
),
expect![[r#"digraph test_some_labelled {
N0[label="A"];
N1[label="N1"][style="dotted"];
N0 -> N1[label="A-1"][arrowhead="lcrow" dir="both" arrowtail="tee"];
}
"#]],
);
}
#[test]
fn badly_formatted_id() {
let id2 = Id::new("Weird { struct : ure } !!!");
assert!(
id2.is_err(),
"graphviz id suddenly allows spaces, brackets and stuff"
);
}
type SimpleEdge = (Node, Node);
type Subgraph = usize;
struct DefaultStyleGraph {
name: &'static str,
nodes: usize,
edges: Vec<SimpleEdge>,
subgraphs: Vec<Vec<Node>>,
kind: Kind,
rankdir: Option<RankDir>,
}
impl DefaultStyleGraph {
fn new(
name: &'static str,
nodes: usize,
edges: Vec<SimpleEdge>,
subgraphs: Vec<Vec<Node>>,
kind: Kind,
) -> DefaultStyleGraph {
assert!(!name.is_empty());
DefaultStyleGraph {
name,
nodes,
edges,
subgraphs,
kind,
rankdir: None,
}
}
fn with_rankdir(self, rankdir: Option<RankDir>) -> Self {
Self { rankdir, ..self }
}
}
impl<'a> Labeller<'a, Node, &'a SimpleEdge, Subgraph> for DefaultStyleGraph {
fn graph_id(&'a self) -> Id<'a> {
Id::new(self.name).unwrap()
}
fn node_id(&'a self, n: &Node) -> Id<'a> {
id_name(n)
}
fn kind(&self) -> Kind {
self.kind
}
fn subgraph_id(&'a self, s: &Subgraph) -> Option<Id<'a>> {
Id::new(format!("cluster_{}", s)).ok()
}
fn rank_dir(&self) -> Option<RankDir> {
self.rankdir
}
}
impl<'a> GraphWalk<'a, Node, &'a SimpleEdge, Subgraph> for DefaultStyleGraph {
fn nodes(&'a self) -> Nodes<'a, Node> {
(0..self.nodes).collect()
}
fn edges(&'a self) -> Edges<'a, &'a SimpleEdge> {
self.edges.iter().collect()
}
fn source(&'a self, edge: &&'a SimpleEdge) -> Node {
edge.0
}
fn target(&'a self, edge: &&'a SimpleEdge) -> Node {
edge.1
}
fn subgraphs(&'a self) -> Subgraphs<'a, Subgraph> {
std::borrow::Cow::Owned((0..self.subgraphs.len()).collect::<Vec<_>>())
}
fn subgraph_nodes(&'a self, s: &Subgraph) -> Nodes<'a, Node> {
std::borrow::Cow::Borrowed(&self.subgraphs[*s])
}
}
#[test]
fn default_style_graph() {
check_input(
&DefaultStyleGraph::new(
"g",
4,
vec![(0, 1), (0, 2), (1, 3), (2, 3)],
Vec::new(),
Kind::Graph,
),
expect![[r#"graph g {
N0[label="N0"];
N1[label="N1"];
N2[label="N2"];
N3[label="N3"];
N0 -- N1[label=""];
N0 -- N2[label=""];
N1 -- N3[label=""];
N2 -- N3[label=""];
}
"#]],
);
}
#[test]
fn default_style_digraph() {
check_input(
&DefaultStyleGraph::new(
"di",
4,
vec![(0, 1), (0, 2), (1, 3), (2, 3)],
Vec::new(),
Kind::Digraph,
),
expect![[r#"digraph di {
N0[label="N0"];
N1[label="N1"];
N2[label="N2"];
N3[label="N3"];
N0 -> N1[label=""];
N0 -> N2[label=""];
N1 -> N3[label=""];
N2 -> N3[label=""];
}
"#]],
);
}
#[test]
fn digraph_with_rankdir() {
check_input(
&DefaultStyleGraph::new("di", 4, vec![(0, 1), (0, 2)], Vec::new(), Kind::Digraph)
.with_rankdir(Some(RankDir::LeftRight)),
expect![[r#"digraph di {
rankdir="LR";
N0[label="N0"];
N1[label="N1"];
N2[label="N2"];
N3[label="N3"];
N0 -> N1[label=""];
N0 -> N2[label=""];
}
"#]],
);
}
#[test]
fn subgraph() {
check_input(
&DefaultStyleGraph::new(
"di",
4,
vec![(0, 1), (0, 2), (1, 3), (2, 3)],
vec![vec![0, 1], vec![2, 3]],
Kind::Digraph,
),
expect![[r#"digraph di {
subgraph cluster_0 {
label="";
N0;
N1;
}
subgraph cluster_1 {
label="";
N2;
N3;
}
N0[label="N0"];
N1[label="N1"];
N2[label="N2"];
N3[label="N3"];
N0 -> N1[label=""];
N0 -> N2[label=""];
N1 -> N3[label=""];
N2 -> N3[label=""];
}
"#]],
);
}
#[test]
fn simple_subgraph() {
check_input(
&DefaultStyleGraph::new("simple_subgraph", 2, vec![], vec![vec![0, 1]], Kind::Graph),
expect![[r#"
graph simple_subgraph {
subgraph cluster_0 {
label="";
N0;
N1;
}
N0[label="N0"];
N1[label="N1"];
}
"#]],
);
}
}