Skip to main content

logparse_pretty_print/helpers/
hard_block.rs

1use std::fmt::Debug;
2
3use crate::Text;
4
5use super::*;
6
7/// A soft block is a block that is not required to be on a new line.
8///
9/// ```vk
10/// {a, b, c}
11///
12/// {
13///     a,
14///     b,
15/// }
16/// ```
17#[derive(Clone)]
18pub struct HardBlock<'a, T> {
19    /// The indentation of the soft block
20    pub indent: usize,
21    /// The left hand side of the soft block
22    pub lhs: &'static str,
23    /// The right hand side of the soft block
24    pub rhs: &'static str,
25    /// The joint node of the soft block
26    pub joint: PrettyTree<'a, T>,
27}
28
29impl<'a, T: Text<'a> + Debug> Debug for HardBlock<'a, T> {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        f.debug_struct("HardBlock")
32            .field("indent", &self.indent)
33            .field("lhs", &self.lhs)
34            .field("rhs", &self.rhs)
35            .field("joint", &self.joint)
36            .finish()
37    }
38}
39
40impl<'a, T: Text<'a>> HardBlock<'a, T> {
41    /// Build a new soft block
42    pub fn new(lhs: &'static str, rhs: &'static str) -> Self {
43        Self { lhs, rhs, indent: 4, joint: PrettyTree::line_or_space() }
44    }
45    /// Build a new soft block with the parentheses syntax
46    pub fn parentheses() -> Self {
47        Self::new("(", ")")
48    }
49    /// Build a new soft block with the brackets syntax
50    pub fn brackets() -> Self {
51        Self::new("[", "]")
52    }
53    /// Build a new soft block with the curly braces syntax
54    pub fn curly_braces() -> Self {
55        Self::new("{", "}")
56    }
57    /// Set the joint node of the soft block
58    pub fn with_joint(self, joint: PrettyTree<'a, T>) -> Self {
59        Self { joint, ..self }
60    }
61}
62
63impl<'a, T: Clone + Text<'a>> HardBlock<'a, T> {
64    /// Join a slice of pretty printables with the soft block
65    pub fn join_slice<P: PrettyPrint<'a, T>>(&self, slice: &[P], theme: &PrettyProvider) -> PrettyTree<'a, T> {
66        let mut outer = PrettySequence::new(5);
67        outer += self.lhs;
68        outer += PrettyTree::Hardline;
69        let mut inner = PrettySequence::new(slice.len() * 2);
70        for (idx, term) in slice.iter().enumerate() {
71            if idx != 0 {
72                inner += self.joint.clone();
73            }
74            inner += term.pretty(theme);
75        }
76        outer += inner.indent(self.indent);
77        outer += PrettyTree::Hardline;
78        outer += self.rhs;
79        outer.into()
80    }
81}