Skip to main content

color_output/text/
impl.rs

1use crate::*;
2
3/// Default implementation for Text with empty content and default styling.
4impl<'a> Default for Text<'a> {
5    #[inline(always)]
6    fn default() -> Self {
7        Text {
8            text: "",
9            color: ColorType::default(),
10            bg_color: ColorType::default(),
11            bold: false,
12            endl: false,
13        }
14    }
15}
16
17impl<'a> Text<'a> {
18    /// Creates a new Text instance from existing configuration.
19    ///
20    /// # Arguments
21    ///
22    /// - `Text` - Source text configuration to clone
23    ///
24    /// # Returns
25    ///
26    /// - `Text` - New instance with cloned configuration
27    #[inline(always)]
28    pub(crate) fn new_from(text: &Text<'a>) -> Self {
29        Self { ..*text }
30    }
31
32    /// Gets the display string as a `Cow` (clone on write).
33    ///
34    /// This method generates a formatted string that represents the text with
35    /// the appropriate color and background color. If the text is bold, it applies
36    /// bold formatting to the text color.
37    ///
38    /// # Returns
39    /// - `Cow<'a, str>`: An owned copy of the formatted string.
40    pub fn get_display_str_cow(&self) -> Cow<'a, str> {
41        let text: &str = self.text;
42        let bold: bool = self.bold;
43        let adjusted_color: ColorType = if matches!(self.color, ColorType::Use(Color::Default)) {
44            ColorContrast::ensure_sufficient_contrast(&self.color, &self.bg_color)
45        } else {
46            self.color
47        };
48        let color: String = adjusted_color.to_string();
49        let bg_color: String = self.bg_color.get_str(DisplayType::Background);
50        let mut colored_text: String = if bold {
51            format!("{CSI}{SGR_BOLD}{SEMICOLON}{bg_color}{SEMICOLON}{color}{SGR}{text}{SGR_RESET}")
52        } else {
53            format!("{CSI}{bg_color}{SEMICOLON}{color}{SGR}{text}{SGR_RESET}")
54        };
55        if self.endl {
56            colored_text.push(LINE_FEED);
57        }
58        Cow::Owned(colored_text)
59    }
60}