Skip to main content

logparse_pretty_print/
text.rs

1use std::borrow::Cow;
2
3/// Pretty printing can work with arbitrary text-like objects,
4/// as long as they implement this trait.
5#[allow(clippy::len_without_is_empty)]
6pub trait Text<'a>: Sized + Clone + 'a {
7    /// Turn a &'static str into Self, without any further knowledge about it.
8    ///
9    /// Used for a bunch of functions to give a default.
10    /// Often not the most optimal or even desired implementation.
11    fn from_static_str(s: &'static str) -> Self;
12
13    /// We foten insert spaces as a static str.
14    ///
15    /// By default this is implemented with [`from_static_str`].
16    fn from_static_spaces(s: &'static str) -> Self {
17        Self::from_static_str(s)
18    }
19
20    /// Turn custom text into a `Cow<'a, str>`.
21    fn as_str(&self) -> Cow<'_, str>;
22
23    /// Get the length of the custom text.
24    fn len(&self) -> usize {
25        str::len(&self.as_str())
26    }
27
28    /// A space character
29    ///
30    /// By default this is implemented with [`from_static_str`].
31    fn space() -> Self {
32        Self::from_static_str(" ")
33    }
34
35    /// A newline character
36    ///
37    /// By default this is implemented with [`from_static_str`].
38    fn newline() -> Self {
39        Self::from_static_str("\n")
40    }
41
42    /// A comma and space character
43    ///
44    /// By default this is implemented with [`from_static_str`].
45    fn comma_space() -> Self {
46        Self::from_static_str(", ")
47    }
48}
49
50impl<'a> Text<'a> for Cow<'a, str> {
51    fn from_static_str(s: &'static str) -> Self {
52        Cow::Borrowed(s)
53    }
54
55    fn as_str(&self) -> Cow<'a, str> {
56        self.clone()
57    }
58}