stylish_core/
display.rs

1use crate::{Formatter, Result};
2
3/// Format trait for the [`stylish` format,
4/// `{:s}`](stylish#implementing-a-style-for-a-type).
5///
6/// `Display` is similar to [`core::fmt::Display`], but allows attaching
7/// additional style attributes to the output.
8///
9/// ```rust
10/// struct Name(&'static str);
11///
12/// impl stylish::Display for Name {
13///     fn fmt(&self, f: &mut stylish::Formatter<'_>) -> stylish::Result {
14///         let color = match self.0 {
15///             "Ferris" => stylish::Color::Red,
16///             "Gorris" => stylish::Color::Cyan,
17///             _ => stylish::Color::Default,
18///         };
19///         f.with(stylish::Foreground(color)).write_str(self.0)
20///     }
21/// }
22///
23/// let formatted = stylish::html::format!("Hello {:s} and {:s}", Name("Ferris"), Name("Gorris"));
24/// assert_eq!(
25///     formatted,
26///     "Hello <span style=color:red>Ferris</span> and <span style=color:cyan>Gorris</span>",
27/// );
28/// ```
29pub trait Display {
30    /// Formats the value using the given formatter.
31    ///
32    /// ```rust
33    /// struct Name(&'static str);
34    ///
35    /// impl stylish::Display for Name {
36    ///     fn fmt(&self, f: &mut stylish::Formatter<'_>) -> stylish::Result {
37    ///         let color = match self.0 {
38    ///             "Ferris" => stylish::Color::Red,
39    ///             "Gorris" => stylish::Color::Cyan,
40    ///             _ => stylish::Color::Default,
41    ///         };
42    ///         f.with(stylish::Foreground(color)).write_str(self.0)
43    ///     }
44    /// }
45    ///
46    /// let formatted = stylish::html::format!("Hello {:s} and {:s}", Name("Ferris"), Name("Gorris"));
47    /// assert_eq!(
48    ///     formatted,
49    ///     "Hello <span style=color:red>Ferris</span> and <span style=color:cyan>Gorris</span>",
50    /// );
51    /// ```
52    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
53}
54
55impl<T: Display + ?Sized> Display for &T {
56    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
57        (**self).fmt(f)
58    }
59}