sodg/
debug.rs

1// Copyright (c) 2022-2023 Yegor Bugayenko
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included
11// in all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21use crate::Sodg;
22use anyhow::{Context, Result};
23use std::fmt;
24use std::fmt::{Debug, Display, Formatter};
25
26impl Display for Sodg {
27    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
28        <&Self as Debug>::fmt(&self, f)
29    }
30}
31
32impl Debug for Sodg {
33    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
34        let mut lines = vec![];
35        for (i, v) in &self.vertices {
36            let mut attrs = v
37                .edges
38                .iter()
39                .map(|e| format!("\n\t{} ➞ ν{}", e.a, e.to))
40                .collect::<Vec<String>>();
41            if !&v.data.is_empty() {
42                attrs.push(format!("{}", v.data));
43            }
44            lines.push(format!("ν{i} -> ⟦{}⟧", attrs.join(", ")));
45        }
46        f.write_str(lines.join("\n").as_str())
47    }
48}
49
50impl Sodg {
51    /// Print a single vertex to a string, which can be used for
52    /// logging and debugging.
53    ///
54    /// # Errors
55    ///
56    /// If the vertex is absent, an error may be returned.
57    pub fn v_print(&self, v: u32) -> Result<String> {
58        let vtx = self.vertices.get(&v).context(format!("Can't find ν{v}"))?;
59        let list: Vec<String> = vtx.edges.iter().map(|e| e.a.clone()).collect();
60        Ok(format!(
61            "ν{v}⟦{}{}⟧",
62            if vtx.data.is_empty() { "" } else { "Δ, " },
63            list.join(", ")
64        ))
65    }
66}
67
68#[test]
69fn prints_itself() -> Result<()> {
70    let mut g = Sodg::empty();
71    g.add(0)?;
72    g.add(1)?;
73    assert_ne!("", format!("{:?}", g));
74    Ok(())
75}
76
77#[test]
78fn displays_itself() -> Result<()> {
79    let mut g = Sodg::empty();
80    g.add(0)?;
81    g.add(1)?;
82    assert_ne!("", format!("{g}"));
83    Ok(())
84}