sodg/inspect.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::DeadRelay;
22use crate::Sodg;
23use anyhow::{Context, Result};
24use itertools::Itertools;
25use std::collections::HashSet;
26
27impl Sodg {
28 /// Find an object by the provided locator and print its tree
29 /// of sub-objects and edges.
30 ///
31 /// The function is mostly used for testing.
32 ///
33 /// # Errors
34 ///
35 /// If it's impossible to inspect, an error will be returned.
36 pub fn inspect(&self, loc: &str) -> Result<String> {
37 let v = self
38 .find(0, loc, &DeadRelay::default())
39 .context(format!("Can't locate '{loc}'"))?;
40 let mut seen = HashSet::new();
41 Ok(format!(
42 "{}/ν{}\n{}",
43 loc,
44 v,
45 self.inspect_v(v, &mut seen)?.join("\n")
46 ))
47 }
48
49 fn inspect_v(&self, v: u32, seen: &mut HashSet<u32>) -> Result<Vec<String>> {
50 seen.insert(v);
51 let mut lines = vec![];
52 self.vertices
53 .get(&v)
54 .context(format!("Can't find ν{v}"))?
55 .edges
56 .iter()
57 .sorted()
58 .for_each(|e| {
59 let skip = seen.contains(&e.to);
60 let line = format!(
61 " .{} ➞ ν{}{}",
62 e.a,
63 e.to,
64 if skip {
65 "…".to_string()
66 } else {
67 String::new()
68 }
69 );
70 lines.push(line);
71 if !skip {
72 seen.insert(e.to);
73 self.inspect_v(e.to, seen)
74 .unwrap()
75 .iter()
76 .for_each(|t| lines.push(format!(" {t}")));
77 }
78 });
79 Ok(lines)
80 }
81}
82
83#[cfg(test)]
84use crate::Hex;
85
86#[test]
87fn inspects_simple_object() -> Result<()> {
88 let mut g = Sodg::empty();
89 g.add(0)?;
90 g.put(0, &Hex::from_str_bytes("hello"))?;
91 g.add(1)?;
92 g.bind(0, 1, "foo")?;
93 let txt = g.inspect("")?;
94 println!("{}", txt);
95 assert_ne!("".to_string(), txt);
96 Ok(())
97}