From 389d25e30f05d8757e0ab359dd0142d76ac29359 Mon Sep 17 00:00:00 2001 From: ridiculousfish Date: Sun, 5 Mar 2023 19:52:13 -0800 Subject: [PATCH] Allow sprintf! to work with literal format strings Now sprintf! has two modes: - Literal format string - Widechar runtime-format string --- fish-rust/src/wutil/format/printf.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/fish-rust/src/wutil/format/printf.rs b/fish-rust/src/wutil/format/printf.rs index 1153a2b40..0324ee96f 100644 --- a/fish-rust/src/wutil/format/printf.rs +++ b/fish-rust/src/wutil/format/printf.rs @@ -115,6 +115,16 @@ fn vsprintfp(format: &[FormatElement], args: &[&dyn Printf]) -> Result /// /// Wrapper around [vsprintf]. macro_rules! sprintf { + // Variant which allows a string literal. + ( + $fmt:literal, // format string + $($arg:expr),* // arguments + $(,)? // optional trailing comma + ) => { + crate::wutil::format::printf::vsprintf(&crate::wchar::L!($fmt), &[$( &($arg) as &dyn crate::wutil::format::printf::Printf),* ][..]).expect("Invalid format string and/or arguments") + }; + + // Variant which allows a runtime format string, which must be of type &wstr. ( $fmt:expr, // format string $($arg:expr),* // arguments @@ -123,4 +133,19 @@ macro_rules! sprintf { crate::wutil::format::printf::vsprintf($fmt, &[$( &($arg) as &dyn crate::wutil::format::printf::Printf),* ][..]).expect("Invalid format string and/or arguments") }; } + pub(crate) use sprintf; + +#[cfg(test)] +mod tests { + use super::*; + use crate::wchar::L; + + // Test basic printf with both literals and wide strings. + #[test] + fn test_sprintf() { + assert_eq!(sprintf!("Hello, %s!", "world"), "Hello, world!"); + assert_eq!(sprintf!(L!("Hello, %ls!"), "world"), "Hello, world!"); + assert_eq!(sprintf!(L!("Hello, %ls!"), L!("world")), "Hello, world!"); + } +}