text_fx/style.rs
1/// A wrapper for text with an associated style label, for diagnostics or formatting.
2///
3/// `StyledText` is a simple struct that pairs a style name (such as `"error"`, `"info"`, etc.)
4/// with a text value. It is useful for tagging text with semantic meaning for later formatting,
5/// such as coloring or styling in diagnostics or logs.
6///
7/// The [`Debug`] implementation prints the text wrapped in XML-like tags using the style name.
8///
9/// # Examples
10///
11/// ```
12/// use text_fx::style::StyledText;
13///
14/// let styled = StyledText::new("warning", "be careful!");
15/// assert_eq!(format!("{:?}", styled), "<warning>be careful!</warning>");
16/// ```
17pub struct StyledText<'a> {
18 style: &'a str,
19 text: &'a str,
20}
21
22impl<'a> StyledText<'a> {
23 /// Create a new `StyledText` with the given style and text.
24 pub fn new(style: &'a str, text: &'a str) -> Self {
25 Self { style, text }
26 }
27}
28
29impl<'a> std::fmt::Debug for StyledText<'a> {
30 /// Formats the styled text as `<style>text</style>`.
31 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 write!(f, "<{}>{}</{}>", self.style, self.text, self.style)
33 }
34}
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39
40 #[test]
41 fn test_styled_text() {
42 let styled = StyledText {
43 style: "error",
44 text: "test",
45 };
46 let s = format!("{:?}", styled);
47 assert_eq!(s, "<error>test</error>");
48 }
49}