1#![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
279pub enum LabelText<'a> {
281    LabelStr(Cow<'a, str>),
286
287    EscStr(Cow<'a, str>),
298
299    HtmlStr(Cow<'a, str>),
305}
306
307#[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#[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
362pub 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    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
467pub trait Labeller<'a, N, E> {
477    fn graph_id(&'a self) -> Id<'a>;
479
480    fn graph_attrs(&'a self) -> HashMap<&str, &str> {
482        HashMap::default()
483    }
484
485    fn node_id(&'a self, n: &N) -> Id<'a>;
489
490    fn node_shape(&'a self, _node: &N) -> Option<LabelText<'a>> {
495        None
496    }
497
498    fn node_label(&'a self, n: &N) -> LabelText<'a> {
502        LabelStr(self.node_id(n).name())
503    }
504
505    fn edge_label(&'a self, e: &E) -> LabelText<'a> {
509        let _ignored = e;
510        LabelStr("".into())
511    }
512
513    fn node_style(&'a self, _n: &N) -> Style {
515        Style::None
516    }
517
518    fn rank_dir(&'a self) -> Option<RankDir> {
522        None
523    }
524
525    fn node_color(&'a self, _node: &N) -> Option<LabelText<'a>> {
530        None
531    }
532
533    fn node_attrs(&'a self, _n: &N) -> HashMap<&str, &str> {
535        HashMap::default()
536    }
537
538    fn edge_end_arrow(&'a self, _e: &E) -> Arrow {
541        Arrow::default()
542    }
543
544    fn edge_start_arrow(&'a self, _e: &E) -> Arrow {
547        Arrow::default()
548    }
549
550    fn edge_style(&'a self, _e: &E) -> Style {
552        Style::None
553    }
554
555    fn edge_color(&'a self, _e: &E) -> Option<LabelText<'a>> {
560        None
561    }
562
563    fn edge_attrs(&'a self, _e: &E) -> HashMap<&str, &str> {
565        HashMap::default()
566    }
567
568    #[inline]
570    fn kind(&self) -> Kind {
571        Kind::Digraph
572    }
573
574    fn edge_start_point(&'a self, _e: &E) -> Option<CompassPoint> {
577        None
578    }
579
580    fn edge_end_point(&'a self, _e: &E) -> Option<CompassPoint> {
583        None
584    }
585
586    fn edge_start_port(&'a self, _: &E) -> Option<Id<'a>> {
588        None
589    }
590
591    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
626pub fn escape_html(s: &str) -> String {
629    s.replace('&', "&")
630        .replace('"', """)
631        .replace('<', "<")
632        .replace('>', ">")
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            '\\' => 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    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    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    pub fn prefix_line(self, prefix: LabelText) -> LabelText<'static> {
705        prefix.suffix_line(self)
706    }
707
708    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#[derive(Clone, Hash, PartialEq, Eq)]
721pub struct Arrow {
722    pub arrows: Vec<ArrowShape>,
723}
724
725use self::ArrowShape::*;
726
727impl Arrow {
728    fn is_default(&self) -> bool {
730        self.arrows.is_empty()
731    }
732
733    pub fn default() -> Arrow {
735        Arrow { arrows: vec![] }
736    }
737
738    pub fn none() -> Arrow {
740        Arrow {
741            arrows: vec![NoArrow],
742        }
743    }
744
745    pub fn normal() -> Arrow {
747        Arrow {
748            arrows: vec![ArrowShape::normal()],
749        }
750    }
751
752    pub fn from_arrow(arrow: ArrowShape) -> Arrow {
754        Arrow {
755            arrows: vec![arrow],
756        }
757    }
758
759    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#[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#[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#[derive(Clone, Copy, Hash, PartialEq, Eq)]
822pub enum ArrowShape {
823    NoArrow,
825    Normal(Fill, Side),
828    Box(Fill, Side),
830    Crow(Side),
832    Curve(Side),
834    ICurve(Fill, Side),
836    Diamond(Fill, Side),
838    Dot(Fill),
840    Inv(Fill, Side),
842    Tee(Side),
844    Vee(Side),
846}
847impl ArrowShape {
848    pub fn none() -> ArrowShape {
850        ArrowShape::NoArrow
851    }
852
853    pub fn normal() -> ArrowShape {
855        ArrowShape::Normal(Fill::Filled, Side::Both)
856    }
857
858    pub fn boxed() -> ArrowShape {
860        ArrowShape::Box(Fill::Filled, Side::Both)
861    }
862
863    pub fn crow() -> ArrowShape {
865        ArrowShape::Crow(Side::Both)
866    }
867
868    pub fn curve() -> ArrowShape {
870        ArrowShape::Curve(Side::Both)
871    }
872
873    pub fn icurve() -> ArrowShape {
875        ArrowShape::ICurve(Fill::Filled, Side::Both)
876    }
877
878    pub fn diamond() -> ArrowShape {
880        ArrowShape::Diamond(Fill::Filled, Side::Both)
881    }
882
883    pub fn dot() -> ArrowShape {
885        ArrowShape::Diamond(Fill::Filled, Side::Both)
886    }
887
888    pub fn inv() -> ArrowShape {
890        ArrowShape::Inv(Fill::Filled, Side::Both)
891    }
892
893    pub fn tee() -> ArrowShape {
895        ArrowShape::Tee(Side::Both)
896    }
897
898    pub fn vee() -> ArrowShape {
900        ArrowShape::Vee(Side::Both)
901    }
902
903    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#[derive(Copy, Clone, PartialEq, Eq, Debug)]
948pub enum Kind {
949    Digraph,
950    Graph,
951}
952
953impl Kind {
954    fn keyword(&self) -> &'static str {
957        match *self {
958            Kind::Digraph => "digraph",
959            Kind::Graph => "graph",
960        }
961    }
962
963    fn edgeop(&self) -> &'static str {
965        match *self {
966            Kind::Digraph => "->",
967            Kind::Graph => "--",
968        }
969    }
970}
971
972pub trait GraphWalk<'a, N: Clone, E: Clone> {
989    fn nodes(&'a self) -> Nodes<'a, N>;
991    fn edges(&'a self) -> Edges<'a, E>;
993    fn source(&'a self, edge: &E) -> N;
995    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
1010pub fn default_options() -> Vec<RenderOption> {
1012    vec![]
1013}
1014
1015pub 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
1030pub 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    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        name: &'static str,
1269
1270        node_labels: Vec<Option<&'static str>>,
1278
1279        node_styles: Vec<Style>,
1280
1281        edges: Vec<Edge>,
1284    }
1285
1286    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    #[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        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}