From 7d3b157f1316550adaf70a2a5eabd37d9be35288 Mon Sep 17 00:00:00 2001 From: Peter Ammon Date: Sat, 8 Mar 2025 20:26:03 -0800 Subject: [PATCH] Allow sprintf! macros to accept format string only This allows something like `sprintf!("foo")`. Previously this was a compile time error. Fixes #11243 --- printf/src/lib.rs | 14 ++++++-------- printf/src/tests.rs | 12 ++++++++++++ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/printf/src/lib.rs b/printf/src/lib.rs index 6e9b7b581..733d7a193 100644 --- a/printf/src/lib.rs +++ b/printf/src/lib.rs @@ -32,13 +32,12 @@ macro_rules! sprintf { // Write to a newly allocated String, and return it. // This panics if the format string or arguments are invalid. ( - $fmt:expr, // Format string, which should implement FormatString. - $($arg:expr),* // arguments - $(,)? // optional trailing comma + $fmt:expr // Format string, which should implement FormatString. + $(, $($arg:expr),*)? // arguments ) => { { let mut target = String::new(); - $crate::sprintf!(=> &mut target, $fmt, $($arg),*); + $crate::sprintf!(=> &mut target, $fmt $(, $($arg),*)?); target } }; @@ -47,9 +46,8 @@ macro_rules! sprintf { // The target should implement std::fmt::Write. ( => $target:expr, // target string - $fmt:expr, // format string - $($arg:expr),* // arguments - $(,)? // optional trailing comma + $fmt:expr // format string + $(, $($arg:expr),*)? // arguments ) => { { // May be no args! @@ -58,7 +56,7 @@ macro_rules! sprintf { $crate::printf_c_locale( $target, $fmt, - &mut [$($arg.to_arg()),*], + &mut [$( $($arg.to_arg()),* )?], ).unwrap() } }; diff --git a/printf/src/tests.rs b/printf/src/tests.rs index fb7446651..85b966af5 100644 --- a/printf/src/tests.rs +++ b/printf/src/tests.rs @@ -659,6 +659,18 @@ fn test_crate_macros() { target = crate::sprintf!("%d ok %d", 3, 4); assert_eq!(target, "3 ok 4"); + + let target = crate::sprintf!("noargs1"); + assert_eq!(target, "noargs1"); + let target = crate::sprintf!("noargs1",); + assert_eq!(target, "noargs1"); + + let mut target = String::new(); + crate::sprintf!(=> &mut target, "noargs2"); + assert_eq!(target, "noargs2"); + let mut target = String::new(); + crate::sprintf!(=> &mut target, "noargs2", ); + assert_eq!(target, "noargs2"); } #[test]