| 1 | /// Format a given string with the passed variables. |
| 2 | /// This macro is creating an single used Hashmap, for performance optimizations it might be |
| 3 | /// more efficient to reuse an existing one. |
| 4 | /// |
| 5 | /// # Arguments |
| 6 | /// * `inst` - A string with an Rust-style format instructions |
| 7 | /// * `values` - A list of values to use for formatting |
| 8 | /// |
| 9 | /// # Errors |
| 10 | /// see [strfmt] |
| 11 | /// |
| 12 | /// # Example |
| 13 | /// ``` |
| 14 | /// use strfmt::FmtError; |
| 15 | /// use strfmt::{strfmt,strfmt_builder}; |
| 16 | /// |
| 17 | /// let fmt = "{first}{second:7.2}"; |
| 18 | /// // ... do stuff and adjust fmt as you need |
| 19 | /// let first = "test"; |
| 20 | /// //test 77.65 |
| 21 | /// println!("{}",strfmt!(fmt, first,second => 77.6543210).unwrap()); |
| 22 | /// ``` |
| 23 | #[macro_export] |
| 24 | macro_rules! strfmt { |
| 25 | ($inst:expr, $($key:ident => $value:tt),*,) => { |
| 26 | strfmt!($inst, $($key => $value)*) |
| 27 | }; |
| 28 | ($inst:expr, $($values:tt),*,) => { |
| 29 | strfmt!($inst, $($values)*) |
| 30 | }; |
| 31 | ($inst:expr,$($values:tt)*) =>({ |
| 32 | use std::collections::HashMap; |
| 33 | use $crate::{DisplayStr,strfmt_builder}; |
| 34 | let mut vars: HashMap<String, Box<dyn DisplayStr>> = HashMap::new(); |
| 35 | strfmt_builder!(vars,$($values)*); |
| 36 | strfmt($inst,&vars) |
| 37 | }); |
| 38 | } |
| 39 | |
| 40 | #[macro_export] |
| 41 | macro_rules! strfmt_builder { |
| 42 | ($vars:expr,$value:expr) => ( |
| 43 | $vars.insert(stringify!($value).to_string(),Box::new($value)); |
| 44 | ); |
| 45 | ($vars:expr,$name:ident => $value:expr) => { |
| 46 | $vars.insert(stringify!($name).to_string(),Box::new($value)); |
| 47 | }; |
| 48 | ($vars:expr,$value:expr,$($values:tt)*) => { |
| 49 | $vars.insert(stringify!($value).to_string(),Box::new($value)); |
| 50 | strfmt_builder!($vars,$($values)*) |
| 51 | }; |
| 52 | ($vars:expr,$name:ident => $value:expr,$($values:tt)*) => { |
| 53 | $vars.insert(stringify!($name).to_string(),Box::new($value)); |
| 54 | strfmt_builder!($vars,$($values)*) |
| 55 | }; |
| 56 | } |