1 //! Macros for string formatting. 2 3 /// Conditionally perform string formatting. 4 /// 5 /// If `$enabled` is true, then do the formatting and return a `Cow::Owned`. 6 /// 7 /// Otherwise, just return the borrowed (often `'static`) string 8 /// `$borrowed`. 9 /// 10 /// When `$enabled` is false, this avoids the overhead of allocating 11 /// and writing to a buffer, as well as any overhead or side effects 12 /// of the format arguments. 13 /// 14 /// # Example 15 /// 16 /// You can use `format_if` to implement a detailed error logging facility 17 /// that can be enabled at runtime. 18 /// 19 /// ``` 20 /// # #[macro_use] extern crate mac; 21 /// # use std::borrow::Cow::{Borrowed, Owned}; 22 /// # fn main() { 23 /// let formatted = format_if!(true, "Vague error", "Error code {:?}", 3); 24 /// 25 /// assert_eq!(&formatted[..], "Error code 3"); 26 /// if let Borrowed(_) = formatted { 27 /// panic!("Wrong!") 28 /// } 29 /// 30 /// let not_formatted = format_if!(false, "Vague error", "Error code {:?}", { 31 /// // Note that the argument is not evaluated. 32 /// panic!("oops"); 33 /// }); 34 /// 35 /// assert_eq!(¬_formatted[..], "Vague error"); 36 /// if let Owned(_) = not_formatted { 37 /// panic!("Wrong!") 38 /// } 39 /// # } 40 /// ``` 41 #[macro_export] 42 macro_rules! format_if { 43 ($enabled:expr, $borrowed:expr, $fmt:expr, $($args:expr),*) => { 44 if $enabled { 45 ::std::borrow::Cow::Owned(format!($fmt, $($args),*)) as ::std::borrow::Cow<str> 46 } else { 47 ::std::borrow::Cow::Borrowed($borrowed) 48 } 49 } 50 } 51