stylish_core/
format.rs

1use crate::{Arguments, String, Write};
2
3#[cfg(feature = "macros")]
4/// Create a [`stylish::String`] using interpolation of runtime elements.
5///
6/// The first argument `format!` receives is a format string literal, the rest
7/// are parameters interpolated based on the format string. See the main
8/// [`stylish`] docs for more info on how the interpolation is controlled.
9///
10/// ```rust
11/// let s: stylish::String = stylish::format!("Hello {:(fg=green)}!", "World");
12///
13/// assert_eq!(
14///     stylish::html::format!("{:s}", s),
15///     "Hello <span style=color:green>World</span>!",
16/// );
17/// ```
18#[macro_export]
19macro_rules! format {
20    ($($arg:tt)*) => {{
21        let res = $crate::format($crate::format_args!($($arg)*));
22        res
23    }};
24}
25
26/// The `format` function takes a [`stylish::Arguments`] struct and returns the
27/// resulting attributed and formatted [`stylish::String`].
28///
29/// The [`stylish::Arguments`] instance can be created with the
30/// [`stylish::format_args!`] macro.
31///
32/// # Examples
33///
34/// Basic usage:
35///
36/// ```rust
37/// let s = stylish::format(stylish::format_args!(
38///     "Hello, {:(fg=green)}!",
39///     "world"
40/// ));
41/// assert_eq!(
42///     stylish::html::format!("{:s}", s),
43///     "Hello, <span style=color:green>world</span>!"
44/// );
45/// ```
46///
47///
48/// Please note that using [`stylish::format!`] might be preferable. Example:
49///
50/// ```rust
51/// let s = stylish::format!("Hello, {:(fg=green)}!", "world");
52/// assert_eq!(
53///     stylish::html::format!("{:s}", s),
54///     "Hello, <span style=color:green>world</span>!"
55/// );
56/// ```
57#[inline]
58pub fn format(args: Arguments<'_>) -> String {
59    let mut output = String::new();
60    output
61        .write_fmt(args)
62        .expect("a formatting trait implementation returned an error");
63    output
64}