#![crate_name = "dot3"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![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::prelude::*;
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,
Solid,
Dashed,
Dotted,
Bold,
Rounded,
Diagonals,
Filled,
Striped,
Wedged,
}
impl Style {
pub fn as_slice(self) -> &'static str {
match self {
Style::None => "",
Style::Solid => "solid",
Style::Dashed => "dashed",
Style::Dotted => "dotted",
Style::Bold => "bold",
Style::Rounded => "rounded",
Style::Diagonals => "diagonals",
Style::Filled => "filled",
Style::Striped => "striped",
Style::Wedged => "wedged",
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum RankDir {
TopBottom,
LeftRight,
BottomTop,
RightLeft,
}
impl RankDir {
pub fn as_slice(self) -> &'static str {
match self {
RankDir::TopBottom => "TB",
RankDir::LeftRight => "LR",
RankDir::BottomTop => "BT",
RankDir::RightLeft => "RL",
}
}
}
pub struct Id<'a> {
name: Cow<'a, str>,
}
#[derive(Debug)]
pub enum IdError {
EmptyName,
InvalidStartChar(char),
InvalidChar(char),
}
impl std::fmt::Display for IdError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
IdError::EmptyName => write!(f, "Id cannot be empty"),
IdError::InvalidStartChar(c) => write!(f, "Id cannot begin with '{c}'"),
IdError::InvalidChar(c) => write!(f, "Id cannot contain '{c}'"),
}
}
}
impl std::error::Error for IdError {}
impl<'a> Id<'a> {
pub fn new<Name: Into<Cow<'a, str>>>(name: Name) -> Result<Id<'a>, IdError> {
let name = name.into();
{
let mut chars = name.chars();
match chars.next() {
Some(c) if is_letter_or_underscore(c) => {}
Some(c) => return Err(IdError::InvalidStartChar(c)),
_ => return Err(IdError::EmptyName),
}
if let Some(bad) = chars.find(|c| !is_constituent(*c)) {
return Err(IdError::InvalidChar(bad));
}
}
return Ok(Id { name });
fn is_letter_or_underscore(c: char) -> bool {
in_range('a', c, 'z') || in_range('A', c, 'Z') || c == '_'
}
fn is_constituent(c: char) -> bool {
is_letter_or_underscore(c) || in_range('0', c, '9')
}
fn in_range(low: char, c: char, high: char) -> bool {
low as usize <= c as usize && c as usize <= high as usize
}
}
pub fn as_slice(&'a self) -> &'a str {
&*self.name
}
pub fn name(self) -> Cow<'a, str> {
self.name
}
}
pub trait Labeller<'a, N, E> {
fn graph_id(&'a self) -> Id<'a>;
fn graph_attrs(&'a self) -> HashMap<&str, &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<&str, &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<&str, &str> {
HashMap::default()
}
#[inline]
fn kind(&self) -> Kind {
Kind::Digraph
}
fn edge_start_point(&'a self, _e: &E) -> Option<CompassPoint> {
None
}
fn edge_end_point(&'a self, _e: &E) -> Option<CompassPoint> {
None
}
fn edge_start_port(&'a self, _: &E) -> Option<Id<'a>> {
None
}
fn edge_end_port(&'a self, _: &E) -> Option<Id<'a>> {
None
}
}
pub enum CompassPoint {
North,
NorthEast,
East,
SouthEast,
South,
SouthWest,
West,
NorthWest,
Center,
}
impl CompassPoint {
const fn to_code(&self) -> &'static str {
use CompassPoint::*;
match self {
North => ":n",
NorthEast => ":ne",
East => ":e",
SouthEast => ":se",
South => ":s",
SouthWest => ":sw",
West => ":w",
NorthWest => ":nw",
Center => ":c",
}
}
}
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) -> LabelText<'a> {
LabelStr(s.into())
}
pub fn escaped<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
EscStr(s.into())
}
pub fn html<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
HtmlStr(s.into())
}
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 {
s.chars().flat_map(|c| c.escape_default()).collect()
}
pub fn to_dot_string(&self) -> String {
match self {
LabelStr(ref s) => format!("\"{}\"", LabelText::escape_default(s)),
EscStr(ref s) => format!("\"{}\"", LabelText::escape_str(&s[..])),
HtmlStr(ref 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, 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 default() -> Arrow {
Arrow { arrows: vec![] }
}
pub fn none() -> Arrow {
Arrow {
arrows: vec![NoArrow],
}
}
pub fn normal() -> Arrow {
Arrow {
arrows: vec![ArrowShape::normal()],
}
}
pub fn from_arrow(arrow: ArrowShape) -> Arrow {
Arrow {
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
}
}
macro_rules! arrowshape_to_arrow {
($n:expr) => {
impl From<[ArrowShape; $n]> for Arrow {
fn from(shape: [ArrowShape; $n]) -> Arrow {
Arrow {
arrows: shape.to_vec(),
}
}
}
};
}
arrowshape_to_arrow!(2);
arrowshape_to_arrow!(3);
arrowshape_to_arrow!(4);
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub enum Fill {
Open,
Filled,
}
impl Fill {
pub fn as_slice(self) -> &'static str {
match self {
Fill::Open => "o",
Fill::Filled => "",
}
}
}
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub enum Side {
Left,
Right,
Both,
}
impl Side {
pub fn as_slice(self) -> &'static str {
match self {
Side::Left => "l",
Side::Right => "r",
Side::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() -> ArrowShape {
ArrowShape::NoArrow
}
pub fn normal() -> ArrowShape {
ArrowShape::Normal(Fill::Filled, Side::Both)
}
pub fn boxed() -> ArrowShape {
ArrowShape::Box(Fill::Filled, Side::Both)
}
pub fn crow() -> ArrowShape {
ArrowShape::Crow(Side::Both)
}
pub fn curve() -> ArrowShape {
ArrowShape::Curve(Side::Both)
}
pub fn icurve() -> ArrowShape {
ArrowShape::ICurve(Fill::Filled, Side::Both)
}
pub fn diamond() -> ArrowShape {
ArrowShape::Diamond(Fill::Filled, Side::Both)
}
pub fn dot() -> ArrowShape {
ArrowShape::Diamond(Fill::Filled, Side::Both)
}
pub fn inv() -> ArrowShape {
ArrowShape::Inv(Fill::Filled, Side::Both)
}
pub fn tee() -> ArrowShape {
ArrowShape::Tee(Side::Both)
}
pub fn vee() -> ArrowShape {
ArrowShape::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_slice());
match side {
Side::Left | Side::Right => res.push_str(side.as_slice()),
Side::Both => {}
};
}
Dot(fill) => res.push_str(fill.as_slice()),
Crow(side) | Curve(side) | Tee(side) | Vee(side) => match side {
Side::Left | Side::Right => res.push_str(side.as_slice()),
Side::Both => {}
},
NoArrow => {}
};
match *self {
NoArrow => res.push_str("none"),
Normal(_, _) => res.push_str("normal"),
Box(_, _) => res.push_str("box"),
Crow(_) => res.push_str("crow"),
Curve(_) => res.push_str("curve"),
ICurve(_, _) => res.push_str("icurve"),
Diamond(_, _) => res.push_str("diamond"),
Dot(_) => res.push_str("dot"),
Inv(_, _) => res.push_str("inv"),
Tee(_) => res.push_str("tee"),
Vee(_) => res.push_str("vee"),
};
res
}
}
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 {
Kind::Digraph => "digraph",
Kind::Graph => "graph",
}
}
fn edgeop(&self) -> &'static str {
match *self {
Kind::Digraph => "->",
Kind::Graph => "--",
}
}
}
pub trait GraphWalk<'a, N: Clone, E: 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;
}
#[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,
G: Labeller<'a, N, E> + GraphWalk<'a, N, E>,
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,
G: Labeller<'a, N, E> + GraphWalk<'a, N, E>,
W: Write,
>(
g: &'a G,
w: &mut W,
options: &[RenderOption],
) -> io::Result<()> {
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" ")
}
writeln(w, &[g.kind().keyword(), " ", g.graph_id().as_slice(), " {"])?;
for (name, value) in g.graph_attrs().iter() {
writeln(w, &[name, "=", value])?;
}
if g.kind() == Kind::Digraph {
if let Some(rankdir) = g.rank_dir() {
indent(w)?;
writeln(w, &["rankdir=\"", rankdir.as_slice(), "\";"])?;
}
}
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_slice()];
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_slice());
text.push("\"]");
}
let color = g.node_color(n);
if !options.contains(&RenderOption::NoNodeColors) {
if 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)?;
}
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();
let start_port = g
.edge_start_port(e)
.map(|p| format!(":{}", p.name()))
.unwrap_or_default();
let end_port = g
.edge_end_port(e)
.map(|p| format!(":{}", p.name()))
.unwrap_or_default();
let start_p = g.edge_start_point(e).map(|p| p.to_code()).unwrap_or("");
let end_p = g.edge_end_point(e).map(|p| p.to_code()).unwrap_or("");
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_slice(),
&start_port,
start_p,
" ",
g.kind().edgeop(),
" ",
target_id.as_slice(),
&end_port,
end_p,
];
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_slice());
text.push("\"]");
}
let color = g.edge_color(e);
if !options.contains(&RenderOption::NoEdgeColors) {
if 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)?;
}
writeln(w, &["}"])
}
#[cfg(test)]
mod tests {
use self::NodeLabels::*;
use super::LabelText::{self, EscStr, HtmlStr, LabelStr};
use super::{render, Edges, GraphWalk, Id, Kind, Labeller, Nodes, RankDir, Style};
use super::{Arrow, ArrowShape, Side};
use std::io;
use std::io::prelude::*;
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: from,
to: to,
label: label,
style: style,
start_arrow: Arrow::default(),
end_arrow: Arrow::default(),
color: 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: from,
to: to,
label: label,
style: style,
start_arrow: start_arrow,
end_arrow: end_arrow,
color: 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(|l| Some(l)).collect(),
SomeNodesLabelled(lbls) => lbls.into_iter().collect(),
}
}
fn len(&self) -> usize {
match self {
&UnlabelledNodes(len) => len,
&AllNodesLabelled(ref lbls) => lbls.len(),
&SomeNodesLabelled(ref lbls) => lbls.len(),
}
}
}
impl LabelledGraph {
fn new(
name: &'static str,
node_labels: Trivial,
edges: Vec<Edge>,
node_styles: Option<Vec<Style>>,
) -> LabelledGraph {
let count = node_labels.len();
LabelledGraph {
name: name,
node_labels: node_labels.into_opt_strs(),
edges: 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>,
) -> LabelledGraphWithEscStrs {
LabelledGraphWithEscStrs {
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(ref 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>> {
match e.color {
Some(l) => Some(LabelStr((*l).into())),
None => None,
}
}
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)) | Some(EscStr(s)) | Some(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)) | Some(EscStr(s)) | Some(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 test_input(g: LabelledGraph) -> io::Result<String> {
let mut writer = Vec::new();
render(&g, &mut writer).unwrap();
let mut s = String::new();
Read::read_to_string(&mut &*writer, &mut s)?;
Ok(s)
}
#[test]
fn empty_graph() {
let labels: Trivial = UnlabelledNodes(0);
let r = test_input(LabelledGraph::new("empty_graph", labels, vec![], None));
assert_eq!(
r.unwrap(),
r#"digraph empty_graph {
}
"#
);
}
#[test]
fn single_node() {
let labels: Trivial = UnlabelledNodes(1);
let r = test_input(LabelledGraph::new("single_node", labels, vec![], None));
assert_eq!(
r.unwrap(),
r#"digraph single_node {
N0[label="N0"];
}
"#
);
}
#[test]
fn single_node_with_style() {
let labels: Trivial = UnlabelledNodes(1);
let styles = Some(vec![Style::Dashed]);
let r = test_input(LabelledGraph::new("single_node", labels, vec![], styles));
assert_eq!(
r.unwrap(),
r#"digraph single_node {
N0[label="N0"][style="dashed"];
}
"#
);
}
#[test]
fn single_edge() {
let labels: Trivial = UnlabelledNodes(2);
let result = test_input(LabelledGraph::new(
"single_edge",
labels,
vec![edge(0, 1, "E", Style::None, None)],
None,
));
assert_eq!(
result.unwrap(),
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);
let result = test_input(LabelledGraph::new(
"single_edge",
labels,
vec![edge(0, 1, "E", Style::Bold, Some("red"))],
None,
));
assert_eq!(
result.unwrap(),
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]);
let result = test_input(LabelledGraph::new(
"test_some_labelled",
labels,
vec![edge(0, 1, "A-1", Style::None, None)],
styles,
));
assert_eq!(
result.unwrap(),
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);
let r = test_input(LabelledGraph::new(
"single_cyclic_node",
labels,
vec![edge(0, 0, "E", Style::None, None)],
None,
));
assert_eq!(
r.unwrap(),
r#"digraph single_cyclic_node {
N0[label="N0"];
N0 -> N0[label="E"];
}
"#
);
}
#[test]
fn hasse_diagram() {
let labels = AllNodesLabelled(vec!["{x,y}", "{x}", "{y}", "{}"]);
let r = test_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,
));
assert_eq!(
r.unwrap(),
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 left_aligned_text() {
let labels = AllNodesLabelled(vec![
"if test {\
\\l branch1\
\\l} else {\
\\l branch2\
\\l}\
\\lafterward\
\\l",
"branch1",
"branch2",
"afterward",
]);
let mut writer = Vec::new();
let g = 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),
],
);
render(&g, &mut writer).unwrap();
let mut r = String::new();
Read::read_to_string(&mut &*writer, &mut r).unwrap();
assert_eq!(
r,
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");
match id1 {
Ok(_) => {}
Err(..) => panic!("'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());
let result = test_input(LabelledGraph::new(
"test_some_labelled",
labels,
vec![edge_with_arrows(0, 1, "A-1", Style::None, start, end, None)],
styles,
));
assert_eq!(
result.unwrap(),
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));
let result = test_input(LabelledGraph::new(
"test_some_labelled",
labels,
vec![edge_with_arrows(0, 1, "A-1", Style::None, start, end, None)],
styles,
));
assert_eq!(
result.unwrap(),
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 } !!!");
match id2 {
Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),
Err(..) => {}
}
}
type SimpleEdge = (Node, Node);
struct DefaultStyleGraph {
name: &'static str,
nodes: usize,
edges: Vec<SimpleEdge>,
kind: Kind,
rankdir: Option<RankDir>,
}
impl DefaultStyleGraph {
fn new(
name: &'static str,
nodes: usize,
edges: Vec<SimpleEdge>,
kind: Kind,
) -> DefaultStyleGraph {
assert!(!name.is_empty());
DefaultStyleGraph {
name: name,
nodes: nodes,
edges: edges,
kind: kind,
rankdir: None,
}
}
fn with_rankdir(self, rankdir: Option<RankDir>) -> Self {
Self { rankdir, ..self }
}
}
impl<'a> Labeller<'a, Node, &'a SimpleEdge> 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 rank_dir(&self) -> Option<RankDir> {
self.rankdir
}
}
impl<'a> GraphWalk<'a, Node, &'a SimpleEdge> 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 test_input_default(g: DefaultStyleGraph) -> io::Result<String> {
let mut writer = Vec::new();
render(&g, &mut writer).unwrap();
let mut s = String::new();
Read::read_to_string(&mut &*writer, &mut s)?;
Ok(s)
}
#[test]
fn default_style_graph() {
let r = test_input_default(DefaultStyleGraph::new(
"g",
4,
vec![(0, 1), (0, 2), (1, 3), (2, 3)],
Kind::Graph,
));
assert_eq!(
r.unwrap(),
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() {
let r = test_input_default(DefaultStyleGraph::new(
"di",
4,
vec![(0, 1), (0, 2), (1, 3), (2, 3)],
Kind::Digraph,
));
assert_eq!(
r.unwrap(),
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() {
let r = test_input_default(
DefaultStyleGraph::new("di", 4, vec![(0, 1), (0, 2)], Kind::Digraph)
.with_rankdir(Some(RankDir::LeftRight)),
);
assert_eq!(
r.unwrap(),
r#"digraph di {
rankdir="LR";
N0[label="N0"];
N1[label="N1"];
N2[label="N2"];
N3[label="N3"];
N0 -> N1[label=""];
N0 -> N2[label=""];
}
"#
);
}
}