diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
commit | 698f8c2f01ea549d77d7dc3338a12e04c11057b9 (patch) | |
tree | 173a775858bd501c378080a10dca74132f05bc50 /vendor/mac/src/format.rs | |
parent | Initial commit. (diff) | |
download | rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.tar.xz rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.zip |
Adding upstream version 1.64.0+dfsg1.upstream/1.64.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/mac/src/format.rs')
-rw-r--r-- | vendor/mac/src/format.rs | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/vendor/mac/src/format.rs b/vendor/mac/src/format.rs new file mode 100644 index 000000000..8d4c8bb09 --- /dev/null +++ b/vendor/mac/src/format.rs @@ -0,0 +1,50 @@ +//! Macros for string formatting. + +/// Conditionally perform string formatting. +/// +/// If `$enabled` is true, then do the formatting and return a `Cow::Owned`. +/// +/// Otherwise, just return the borrowed (often `'static`) string +/// `$borrowed`. +/// +/// When `$enabled` is false, this avoids the overhead of allocating +/// and writing to a buffer, as well as any overhead or side effects +/// of the format arguments. +/// +/// # Example +/// +/// You can use `format_if` to implement a detailed error logging facility +/// that can be enabled at runtime. +/// +/// ``` +/// # #[macro_use] extern crate mac; +/// # use std::borrow::Cow::{Borrowed, Owned}; +/// # fn main() { +/// let formatted = format_if!(true, "Vague error", "Error code {:?}", 3); +/// +/// assert_eq!(&formatted[..], "Error code 3"); +/// if let Borrowed(_) = formatted { +/// panic!("Wrong!") +/// } +/// +/// let not_formatted = format_if!(false, "Vague error", "Error code {:?}", { +/// // Note that the argument is not evaluated. +/// panic!("oops"); +/// }); +/// +/// assert_eq!(¬_formatted[..], "Vague error"); +/// if let Owned(_) = not_formatted { +/// panic!("Wrong!") +/// } +/// # } +/// ``` +#[macro_export] +macro_rules! format_if { + ($enabled:expr, $borrowed:expr, $fmt:expr, $($args:expr),*) => { + if $enabled { + ::std::borrow::Cow::Owned(format!($fmt, $($args),*)) as ::std::borrow::Cow<str> + } else { + ::std::borrow::Cow::Borrowed($borrowed) + } + } +} |