| 1 | use crate::graph::rope::Miss; |
| 2 | use crate::graph::{Fork, Graph, Node, NodeId, Range, Rope}; |
| 3 | use std::collections::HashMap; |
| 4 | use std::fmt::{Display, Write}; |
| 5 | |
| 6 | /// Helps assign short strings to node ids while avoiding name collisions. |
| 7 | struct NodeIdStrings { |
| 8 | next: u32, |
| 9 | mappings: HashMap<usize, String>, |
| 10 | } |
| 11 | |
| 12 | impl NodeIdStrings { |
| 13 | fn new() -> Self { |
| 14 | Self { |
| 15 | next: 0, |
| 16 | mappings: HashMap::new(), |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | /// Get a unique string for a node. |
| 21 | fn get_unique(&mut self) -> String { |
| 22 | let next = self.next; |
| 23 | self.next += 1; |
| 24 | format!("n{:x}", next) |
| 25 | } |
| 26 | |
| 27 | /// Get the string assigned to a node from its index. |
| 28 | fn idx(&mut self, id: usize) -> &str { |
| 29 | // Insert cannot be used since we also need a mut ref for get_unique |
| 30 | #[allow(clippy::map_entry)] |
| 31 | if !self.mappings.contains_key(&id) { |
| 32 | let next = self.get_unique(); |
| 33 | self.mappings.insert(id, next); |
| 34 | } |
| 35 | self.mappings.get(&id).unwrap().as_str() |
| 36 | } |
| 37 | |
| 38 | /// Get the string assigned to a node from its id. |
| 39 | fn node(&mut self, node: NodeId) -> &str { |
| 40 | self.idx(node.get()) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | enum NodeColor { |
| 45 | Red, |
| 46 | Blue, |
| 47 | Green, |
| 48 | Orange, |
| 49 | } |
| 50 | |
| 51 | impl NodeColor { |
| 52 | fn fmt_dot(&self) -> &'static str { |
| 53 | match self { |
| 54 | Self::Red => "red", |
| 55 | Self::Blue => "blue", |
| 56 | Self::Green => "green", |
| 57 | Self::Orange => "orange", |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | fn fmt_mmd(&self) -> &'static str { |
| 62 | match self { |
| 63 | Self::Red => "#D50000", |
| 64 | Self::Blue => "#2962FF", |
| 65 | Self::Green => "#00C853", |
| 66 | Self::Orange => "#FF6D00", |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | trait ExportFormat { |
| 72 | fn write_header(s: &mut String) -> std::fmt::Result; |
| 73 | |
| 74 | fn write_footer(s: &mut String) -> std::fmt::Result; |
| 75 | |
| 76 | fn write_node(s: &mut String, id: &str, label: &str, color: NodeColor) -> std::fmt::Result; |
| 77 | |
| 78 | fn write_link(s: &mut String, from: &str, to: &str) -> std::fmt::Result; |
| 79 | |
| 80 | fn fmt_range(r: &Range) -> String; |
| 81 | } |
| 82 | |
| 83 | impl Range { |
| 84 | fn fmt_with_escape<I: Iterator<Item = char>>(&self, escape: impl Fn(char) -> I) -> String { |
| 85 | let fmt_byte = |b: u8| -> String { |
| 86 | if (0x20..0x7F).contains(&b) { |
| 87 | let escaped = (b as char).escape_default().flat_map(&escape); |
| 88 | format!("'{}'", escaped.collect::<String>()) |
| 89 | } else { |
| 90 | format!("{:02X}", b) |
| 91 | } |
| 92 | }; |
| 93 | |
| 94 | if let Some(b) = self.as_byte() { |
| 95 | fmt_byte(b) |
| 96 | } else { |
| 97 | format!("{}..={}", fmt_byte(self.start), fmt_byte(self.end)) |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | struct Dot; |
| 103 | |
| 104 | impl ExportFormat for Dot { |
| 105 | fn write_header(s: &mut String) -> std::fmt::Result { |
| 106 | write!(s, "digraph {{")?; |
| 107 | write!(s, "node[shape=box];")?; |
| 108 | write!(s, "splines=ortho;") |
| 109 | } |
| 110 | |
| 111 | fn write_footer(s: &mut String) -> std::fmt::Result { |
| 112 | write!(s, "}}") |
| 113 | } |
| 114 | |
| 115 | fn write_node(s: &mut String, id: &str, label: &str, color: NodeColor) -> std::fmt::Result { |
| 116 | write!(s, "{}[label=\"{}\",color={}];", id, label, color.fmt_dot()) |
| 117 | } |
| 118 | |
| 119 | fn write_link(s: &mut String, from: &str, to: &str) -> std::fmt::Result { |
| 120 | write!(s, "{}->{};", from, to) |
| 121 | } |
| 122 | |
| 123 | fn fmt_range(r: &Range) -> String { |
| 124 | r.fmt_with_escape(|c| c.escape_default()) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | struct Mermaid; |
| 129 | |
| 130 | impl ExportFormat for Mermaid { |
| 131 | fn write_header(s: &mut String) -> std::fmt::Result { |
| 132 | writeln!(s, "flowchart TB") |
| 133 | } |
| 134 | |
| 135 | fn write_footer(_s: &mut String) -> std::fmt::Result { |
| 136 | Ok(()) |
| 137 | } |
| 138 | |
| 139 | fn write_node(s: &mut String, id: &str, label: &str, color: NodeColor) -> std::fmt::Result { |
| 140 | writeln!(s, "{}[\"{}\"]", id, label)?; |
| 141 | writeln!(s, "style {} stroke:{}", id, color.fmt_mmd()) |
| 142 | } |
| 143 | |
| 144 | fn write_link(s: &mut String, from: &str, to: &str) -> std::fmt::Result { |
| 145 | writeln!(s, "{}-->{}", from, to) |
| 146 | } |
| 147 | |
| 148 | fn fmt_range(r: &Range) -> String { |
| 149 | fn escape_mmd(c: char) -> impl Iterator<Item = char> { |
| 150 | enum Iter { |
| 151 | Char(Option<char>), |
| 152 | Str(std::str::Chars<'static>), |
| 153 | } |
| 154 | |
| 155 | impl Iterator for Iter { |
| 156 | type Item = char; |
| 157 | |
| 158 | fn next(&mut self) -> Option<Self::Item> { |
| 159 | match self { |
| 160 | Iter::Char(c) => c.take(), |
| 161 | Iter::Str(cs) => cs.next(), |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | match c { |
| 166 | '"' => Iter::Str(""".chars()), |
| 167 | '\\' => Iter::Str("\\\\".chars()), |
| 168 | _ => Iter::Char(Some(c)), |
| 169 | } |
| 170 | } |
| 171 | r.fmt_with_escape(escape_mmd) |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | impl<Leaf: Display> Graph<Leaf> { |
| 176 | /// Writes the `Graph` to a dot file. |
| 177 | pub fn get_dot(&self) -> Result<String, std::fmt::Error> { |
| 178 | self.export_graph::<Dot>() |
| 179 | } |
| 180 | |
| 181 | /// Writes the `Graph` to a mermaid file. |
| 182 | pub fn get_mermaid(&self) -> Result<String, std::fmt::Error> { |
| 183 | self.export_graph::<Mermaid>() |
| 184 | } |
| 185 | |
| 186 | fn export_graph<Fmt: ExportFormat>(&self) -> Result<String, std::fmt::Error> { |
| 187 | let mut s = String::new(); |
| 188 | |
| 189 | let entries = self |
| 190 | .nodes() |
| 191 | .iter() |
| 192 | .enumerate() |
| 193 | .filter_map(|(i, n)| n.as_ref().map(|n| (i, n))); |
| 194 | |
| 195 | let mut ids = NodeIdStrings::new(); |
| 196 | |
| 197 | Fmt::write_header(&mut s)?; |
| 198 | for (id, node) in entries { |
| 199 | match node { |
| 200 | Node::Fork(fork) => fork.write_graph::<Fmt>(&mut s, &mut ids, id)?, |
| 201 | Node::Rope(rope) => rope.write_graph::<Fmt>(&mut s, &mut ids, id)?, |
| 202 | Node::Leaf(leaf) => { |
| 203 | Fmt::write_node(&mut s, ids.idx(id), &leaf.to_string(), NodeColor::Green)?; |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | Fmt::write_footer(&mut s)?; |
| 208 | |
| 209 | Ok(s) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | impl Fork { |
| 214 | fn write_graph<Fmt: ExportFormat>( |
| 215 | &self, |
| 216 | s: &mut String, |
| 217 | ids: &mut NodeIdStrings, |
| 218 | id: usize, |
| 219 | ) -> Result<(), std::fmt::Error> { |
| 220 | let id = ids.idx(id).to_string(); |
| 221 | Fmt::write_node(s, &id, "Fork", NodeColor::Blue)?; |
| 222 | for (range, node) in self.branches() { |
| 223 | let link_id = ids.get_unique(); |
| 224 | Fmt::write_node(s, &link_id, &Fmt::fmt_range(&range), NodeColor::Orange)?; |
| 225 | Fmt::write_link(s, &id, &link_id)?; |
| 226 | Fmt::write_link(s, &link_id, ids.node(node))?; |
| 227 | } |
| 228 | if let Some(miss) = self.miss { |
| 229 | Fmt::write_link(s, &id, ids.node(miss))?; |
| 230 | } |
| 231 | Ok(()) |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | impl Rope { |
| 236 | fn write_graph<Fmt: ExportFormat>( |
| 237 | &self, |
| 238 | s: &mut String, |
| 239 | ids: &mut NodeIdStrings, |
| 240 | id: usize, |
| 241 | ) -> Result<(), std::fmt::Error> { |
| 242 | let id = ids.idx(id).to_owned(); |
| 243 | Fmt::write_node(s, &id, "Rope", NodeColor::Blue)?; |
| 244 | |
| 245 | let mut previous = id.clone(); |
| 246 | for range in self.pattern.iter() { |
| 247 | let link_id = ids.get_unique(); |
| 248 | Fmt::write_node(s, &link_id, &Fmt::fmt_range(range), NodeColor::Orange)?; |
| 249 | Fmt::write_link(s, &previous, &link_id)?; |
| 250 | previous = link_id; |
| 251 | } |
| 252 | Fmt::write_link(s, &previous, ids.node(self.then))?; |
| 253 | |
| 254 | match self.miss { |
| 255 | Miss::First(node) => { |
| 256 | let link_id = ids.get_unique(); |
| 257 | Fmt::write_node( |
| 258 | s, |
| 259 | &link_id, |
| 260 | &format!("NOT {}", Fmt::fmt_range(self.pattern.first().unwrap())), |
| 261 | NodeColor::Red, |
| 262 | )?; |
| 263 | Fmt::write_link(s, &id, &link_id)?; |
| 264 | Fmt::write_link(s, &link_id, ids.node(node)) |
| 265 | } |
| 266 | Miss::Any(node) => { |
| 267 | let link_id = ids.get_unique(); |
| 268 | Fmt::write_node(s, &link_id, "MISS", NodeColor::Red)?; |
| 269 | Fmt::write_link(s, &id, &link_id)?; |
| 270 | Fmt::write_link(s, &link_id, ids.node(node)) |
| 271 | } |
| 272 | Miss::None => Ok(()), |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | #[cfg(test)] |
| 278 | mod tests { |
| 279 | use super::*; |
| 280 | use crate::graph::{Fork, NodeId, Range, Rope}; |
| 281 | |
| 282 | #[test] |
| 283 | fn range_fmt_single_ascii_byte() { |
| 284 | let r = Range { |
| 285 | start: 0x6C, |
| 286 | end: 0x6C, |
| 287 | }; |
| 288 | assert_eq!(Dot::fmt_range(&r), "'l'"); |
| 289 | assert_eq!(Mermaid::fmt_range(&r), "'l'"); |
| 290 | } |
| 291 | |
| 292 | #[test] |
| 293 | fn range_fmt_ascii_bytes() { |
| 294 | let r = Range { |
| 295 | start: 0x61, |
| 296 | end: 0x7A, |
| 297 | }; |
| 298 | assert_eq!(Dot::fmt_range(&r), "'a'..='z'"); |
| 299 | assert_eq!(Mermaid::fmt_range(&r), "'a'..='z'"); |
| 300 | } |
| 301 | |
| 302 | #[test] |
| 303 | fn range_fmt_single_escaped_ascii_byte() { |
| 304 | let r = Range { |
| 305 | start: 0x22, |
| 306 | end: 0x22, |
| 307 | }; |
| 308 | assert_eq!(Dot::fmt_range(&r), "'\\\\\\\"'"); |
| 309 | assert_eq!(Mermaid::fmt_range(&r), "'\\\\"'"); |
| 310 | |
| 311 | let r = Range { |
| 312 | start: 0x5C, |
| 313 | end: 0x5C, |
| 314 | }; |
| 315 | assert_eq!(Dot::fmt_range(&r), "'\\\\\\\\'"); |
| 316 | assert_eq!(Mermaid::fmt_range(&r), "'\\\\\\\\'"); |
| 317 | } |
| 318 | |
| 319 | #[test] |
| 320 | fn range_fmt_single_hex_byte() { |
| 321 | let r = Range { |
| 322 | start: 0x0A, |
| 323 | end: 0x0A, |
| 324 | }; |
| 325 | assert_eq!(Dot::fmt_range(&r), "0A"); |
| 326 | assert_eq!(Mermaid::fmt_range(&r), "0A"); |
| 327 | } |
| 328 | |
| 329 | #[test] |
| 330 | fn range_fmt_hex_bytes() { |
| 331 | let r = Range { |
| 332 | start: 0x0A, |
| 333 | end: 0x10, |
| 334 | }; |
| 335 | assert_eq!(Dot::fmt_range(&r), "0A..=10"); |
| 336 | assert_eq!(Mermaid::fmt_range(&r), "0A..=10"); |
| 337 | } |
| 338 | |
| 339 | #[test] |
| 340 | fn node_id_strings() { |
| 341 | let mut ids = NodeIdStrings::new(); |
| 342 | let node_1 = ids.idx(1).to_owned(); |
| 343 | let node_2 = ids.idx(2).to_owned(); |
| 344 | let temp = ids.get_unique().to_owned(); |
| 345 | let node_1_again = ids.node(NodeId::new(1)).to_owned(); |
| 346 | assert_eq!(node_1, node_1_again); |
| 347 | assert_ne!(node_2, temp); |
| 348 | assert_ne!(node_1, node_2); |
| 349 | assert_ne!(node_1, temp); |
| 350 | } |
| 351 | |
| 352 | #[test] |
| 353 | fn fork() { |
| 354 | let n = Fork::new() |
| 355 | .branch( |
| 356 | Range { |
| 357 | start: 0x61, |
| 358 | end: 0x79, |
| 359 | }, |
| 360 | NodeId::new(2), |
| 361 | ) |
| 362 | .branch( |
| 363 | Range { |
| 364 | start: 0x7A, |
| 365 | end: 0x7A, |
| 366 | }, |
| 367 | NodeId::new(3), |
| 368 | ); |
| 369 | |
| 370 | let mut dot = String::new(); |
| 371 | let mut ids = NodeIdStrings::new(); |
| 372 | n.write_graph::<Dot>(&mut dot, &mut ids, 0).unwrap(); |
| 373 | assert_eq!(dot, "n0[label=\"Fork\",color=blue];n1[label=\"'a'..='y'\",color=orange];n0->n1;n1->n2;n3[label=\"'z'\",color=orange];n0->n3;n3->n4;"); |
| 374 | |
| 375 | let mut mmd = String::new(); |
| 376 | let mut ids = NodeIdStrings::new(); |
| 377 | n.write_graph::<Mermaid>(&mut mmd, &mut ids, 0).unwrap(); |
| 378 | assert_eq!(mmd, "n0[\"Fork\"]\nstyle n0 stroke:#2962FF\nn1[\"'a'..='y'\"]\nstyle n1 stroke:#FF6D00\nn0-->n1\nn1-->n2\nn3[\"'z'\"]\nstyle n3 stroke:#FF6D00\nn0-->n3\nn3-->n4\n"); |
| 379 | } |
| 380 | |
| 381 | #[test] |
| 382 | fn fork_with_miss() { |
| 383 | let n = Fork::new() |
| 384 | .branch( |
| 385 | Range { |
| 386 | start: 0x61, |
| 387 | end: 0x7A, |
| 388 | }, |
| 389 | NodeId::new(2), |
| 390 | ) |
| 391 | .miss(NodeId::new(3)); |
| 392 | |
| 393 | let mut dot = String::new(); |
| 394 | let mut ids = NodeIdStrings::new(); |
| 395 | n.write_graph::<Dot>(&mut dot, &mut ids, 0).unwrap(); |
| 396 | assert_eq!(dot, "n0[label=\"Fork\",color=blue];n1[label=\"'a'..='z'\",color=orange];n0->n1;n1->n2;n0->n3;"); |
| 397 | |
| 398 | let mut mmd = String::new(); |
| 399 | let mut ids = NodeIdStrings::new(); |
| 400 | n.write_graph::<Mermaid>(&mut mmd, &mut ids, 0).unwrap(); |
| 401 | assert_eq!(mmd, "n0[\"Fork\"]\nstyle n0 stroke:#2962FF\nn1[\"'a'..='z'\"]\nstyle n1 stroke:#FF6D00\nn0-->n1\nn1-->n2\nn0-->n3\n"); |
| 402 | } |
| 403 | |
| 404 | #[test] |
| 405 | fn rope() { |
| 406 | let n = Rope::new("rope", NodeId::new(1)); |
| 407 | |
| 408 | let mut dot = String::new(); |
| 409 | let mut ids = NodeIdStrings::new(); |
| 410 | n.write_graph::<Dot>(&mut dot, &mut ids, 0).unwrap(); |
| 411 | assert_eq!(dot, "n0[label=\"Rope\",color=blue];n1[label=\"'r'\",color=orange];n0->n1;n2[label=\"'o'\",color=orange];n1->n2;n3[label=\"'p'\",color=orange];n2->n3;n4[label=\"'e'\",color=orange];n3->n4;n4->n5;"); |
| 412 | |
| 413 | let mut mmd = String::new(); |
| 414 | let mut ids = NodeIdStrings::new(); |
| 415 | n.write_graph::<Mermaid>(&mut mmd, &mut ids, 0).unwrap(); |
| 416 | assert_eq!(mmd, "n0[\"Rope\"]\nstyle n0 stroke:#2962FF\nn1[\"'r'\"]\nstyle n1 stroke:#FF6D00\nn0-->n1\nn2[\"'o'\"]\nstyle n2 stroke:#FF6D00\nn1-->n2\nn3[\"'p'\"]\nstyle n3 stroke:#FF6D00\nn2-->n3\nn4[\"'e'\"]\nstyle n4 stroke:#FF6D00\nn3-->n4\nn4-->n5\n"); |
| 417 | } |
| 418 | |
| 419 | #[test] |
| 420 | fn rope_with_miss_first() { |
| 421 | let n = Rope::new("ee", NodeId::new(1)).miss(NodeId::new(2)); |
| 422 | |
| 423 | let mut dot = String::new(); |
| 424 | let mut ids = NodeIdStrings::new(); |
| 425 | n.write_graph::<Dot>(&mut dot, &mut ids, 0).unwrap(); |
| 426 | assert_eq!(dot, "n0[label=\"Rope\",color=blue];n1[label=\"'e'\",color=orange];n0->n1;n2[label=\"'e'\",color=orange];n1->n2;n2->n3;n4[label=\"NOT 'e'\",color=red];n0->n4;n4->n5;"); |
| 427 | |
| 428 | let mut mmd = String::new(); |
| 429 | let mut ids = NodeIdStrings::new(); |
| 430 | n.write_graph::<Mermaid>(&mut mmd, &mut ids, 0).unwrap(); |
| 431 | assert_eq!(mmd, "n0[\"Rope\"]\nstyle n0 stroke:#2962FF\nn1[\"'e'\"]\nstyle n1 stroke:#FF6D00\nn0-->n1\nn2[\"'e'\"]\nstyle n2 stroke:#FF6D00\nn1-->n2\nn2-->n3\nn4[\"NOT 'e'\"]\nstyle n4 stroke:#D50000\nn0-->n4\nn4-->n5\n"); |
| 432 | } |
| 433 | |
| 434 | #[test] |
| 435 | fn rope_with_miss_any() { |
| 436 | let n = Rope::new("ee", NodeId::new(1)).miss_any(NodeId::new(2)); |
| 437 | |
| 438 | let mut dot = String::new(); |
| 439 | let mut ids = NodeIdStrings::new(); |
| 440 | n.write_graph::<Dot>(&mut dot, &mut ids, 0).unwrap(); |
| 441 | assert_eq!(dot, "n0[label=\"Rope\",color=blue];n1[label=\"'e'\",color=orange];n0->n1;n2[label=\"'e'\",color=orange];n1->n2;n2->n3;n4[label=\"MISS\",color=red];n0->n4;n4->n5;"); |
| 442 | |
| 443 | let mut mmd = String::new(); |
| 444 | let mut ids = NodeIdStrings::new(); |
| 445 | n.write_graph::<Mermaid>(&mut mmd, &mut ids, 0).unwrap(); |
| 446 | assert_eq!(mmd, "n0[\"Rope\"]\nstyle n0 stroke:#2962FF\nn1[\"'e'\"]\nstyle n1 stroke:#FF6D00\nn0-->n1\nn2[\"'e'\"]\nstyle n2 stroke:#FF6D00\nn1-->n2\nn2-->n3\nn4[\"MISS\"]\nstyle n4 stroke:#D50000\nn0-->n4\nn4-->n5\n"); |
| 447 | } |
| 448 | } |