Allow sprintf! macros to accept format string only
Some checks are pending
make fish_run_tests / ubuntu (push) Waiting to run
make fish_run_tests / ubuntu-32bit-static-pcre2 (push) Waiting to run
make fish_run_tests / ubuntu-asan (push) Waiting to run
make fish_run_tests / macos (push) Waiting to run
Rust checks / rustfmt (push) Waiting to run
Rust checks / clippy (push) Waiting to run

This allows something like `sprintf!("foo")`. Previously this was a compile time
error.

Fixes #11243
This commit is contained in:
Peter Ammon 2025-03-08 20:26:03 -08:00
parent ad0feab86c
commit 7d3b157f13
No known key found for this signature in database
2 changed files with 18 additions and 8 deletions

View File

@ -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()
}
};

View File

@ -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]