stylish_html/
to_string.rs

1use alloc::string::String;
2
3use stylish_core::Display;
4
5use crate::format;
6
7/// A trait for converting a value to a [`String`] with integrated HTML styling.
8///
9/// This trait is automatically implemented for any type which implements the
10/// [`stylish::Display`] trait. As such, `ToHtmlString` shouldn’t be implemented
11/// directly: [`stylish::Display`] should be implemented instead, and you get
12/// the `ToHtmlString` implementation for free.
13///
14/// [`stylish::Display`]: `stylish_core::Display`
15pub trait ToHtmlString {
16    /// Converts the given value to a [`String`] with integrated HTML styling.
17    ///
18    /// ```rust
19    /// struct Warning(&'static str);
20    ///
21    /// impl stylish::Display for Warning {
22    ///     fn fmt(&self, f: &mut stylish::Formatter<'_>) -> stylish::Result {
23    ///         f.with(stylish::Foreground(stylish::Color::Red))
24    ///             .write_str(self.0)
25    ///     }
26    /// }
27    ///
28    /// use stylish::ToHtmlString;
29    ///
30    /// assert_eq!(
31    ///     Warning("FIRE").to_html_string(),
32    ///     "<span style=color:red>FIRE</span>"
33    /// );
34    /// ```
35    fn to_html_string(&self) -> String;
36}
37
38impl<T> ToHtmlString for T
39where
40    T: Display + ?Sized,
41{
42    fn to_html_string(&self) -> String {
43        format!("{:s}", self)
44    }
45}