Skip to main content

cxx2flow_lib/display/
d2.rs

1use crate::error::{Error, Result};
2use crate::graph::{Graph, GraphNodeType};
3use petgraph::{
4    visit::IntoNodeReferences,
5    visit::{EdgeRef, IntoEdgeReferences},
6};
7
8use super::GraphDisplay;
9#[derive(Debug, Default)]
10pub struct D2 {}
11
12impl D2 {
13    pub fn new() -> Self {
14        D2 {}
15    }
16}
17
18impl GraphDisplay for D2 {
19    fn generate_from_graph(&self, graph: &Graph) -> Result<String> {
20        let mut res = String::new();
21        for (id, i) in graph.node_references() {
22            match i {
23                GraphNodeType::Begin => res.push_str(format!("D{}: begin\n", id.index()).as_str()),
24                GraphNodeType::End => res.push_str(format!("D{}: end\n", id.index()).as_str()),
25                GraphNodeType::Node(str) => res.push_str(
26                    format!(
27                        "D{}: \"{}\"\n",
28                        id.index(),
29                        str.replace('\"', "\\\"").replace('\n', "\\n")
30                    )
31                    .as_str(),
32                ),
33                GraphNodeType::Choice(str) => {
34                    res.push_str(
35                        format!("D{}: \"{}\"\n", id.index(), str.replace('\"', "\\\"")).as_str(),
36                    );
37                    res.push_str(format!("D{}.shape: diamond\n", id.index()).as_str());
38                }
39                GraphNodeType::Dummy => {
40                    return Err(Error::UnexpectedDummyGraphNode {
41                        graph: graph.clone(),
42                    });
43                }
44            }
45        }
46        for i in graph.edge_references() {
47            match i.weight() {
48                crate::graph::EdgeType::Normal => res.push_str(
49                    format!("D{} -> D{}\n", i.source().index(), i.target().index()).as_str(),
50                ),
51                crate::graph::EdgeType::Branch(t) => res.push_str(
52                    format!(
53                        "D{} -> D{}: {}\n",
54                        i.source().index(),
55                        i.target().index(),
56                        if *t { "Y" } else { "N" }
57                    )
58                    .as_str(),
59                ),
60            };
61        }
62        Ok(res)
63    }
64}