Skip to main content

logparse_pretty_print/helpers/
soft_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 SoftBlock<'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    /// The tail node of the soft block
28    pub tail: PrettyTree<'a, T>,
29}
30
31impl<'a, T: Text<'a> + Debug> Debug for SoftBlock<'a, T> {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.debug_struct("SoftBlock")
34            .field("indent", &self.indent)
35            .field("lhs", &self.lhs)
36            .field("rhs", &self.rhs)
37            .field("joint", &self.joint)
38            .field("tail", &self.tail)
39            .finish()
40    }
41}
42
43impl<'a, T: Text<'a>> SoftBlock<'a, T> {
44    /// Build a new soft block
45    pub fn new(lhs: &'static str, rhs: &'static str) -> Self {
46        Self { lhs, rhs, indent: 4, joint: PrettyTree::line_or_space(), tail: PrettyTree::Nil }
47    }
48    /// Build a new soft block with the tuple syntax
49    pub fn tuple() -> Self {
50        Self::new("(", ")")
51    }
52    /// Build a new soft block with the parentheses syntax
53    pub fn parentheses() -> Self {
54        Self::new("(", ")")
55    }
56    /// Build a new soft block with the brackets syntax
57    pub fn brackets() -> Self {
58        Self::new("[", "]")
59    }
60    /// Build a new soft block with the curly braces syntax
61    pub fn curly_braces() -> Self {
62        Self::new("{", "}")
63    }
64    /// Set the joint node of the soft block
65    pub fn with_joint(self, joint: PrettyTree<'a, T>) -> Self {
66        Self { joint, ..self }
67    }
68}
69
70impl<'a, T: Text<'a> + Clone> SoftBlock<'a, T> {
71    /// Join a slice of pretty printables with the soft block
72    pub fn join_slice<U: PrettyPrint<'a, T>>(&self, slice: &[U], theme: &PrettyProvider) -> PrettyTree<'a, T> {
73        let mut outer = PrettySequence::new(5);
74        outer += self.lhs;
75        outer += PrettyTree::line_or_space();
76        let mut inner = PrettySequence::new(slice.len() * 2);
77        for (idx, term) in slice.iter().enumerate() {
78            if idx != 0 {
79                inner += self.joint.clone();
80            }
81            inner += term.pretty(theme);
82        }
83        outer += inner.indent(self.indent);
84        outer += PrettyTree::line_or_space();
85        outer += self.rhs;
86        outer.into()
87    }
88}