Skip to content

Commit 4a8d2e3

Browse files
committed
Auto merge of rust-lang#97480 - conradludgate:faster-format-literals, r=joshtriplett
improve format impl for literals The basic idea of this change can be seen here https://godbolt.org/z/MT37cWoe1. Updates the format impl to have a fast path for string literals and the default path for regular format args. This change will allow `format!("string literal")` to be used interchangably with `"string literal".to_owned()`. This would be relevant in the case of `f!"string literal"` being legal (rust-lang/rfcs#3267) in which case it would be the easiest way to create owned strings from literals, while also being just as efficient as any other impl
2 parents e810f75 + 5dd0fe3 commit 4a8d2e3

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

library/alloc/src/fmt.rs

+9-4
Original file line numberDiff line numberDiff line change
@@ -604,9 +604,14 @@ use crate::string;
604604
#[cfg(not(no_global_oom_handling))]
605605
#[must_use]
606606
#[stable(feature = "rust1", since = "1.0.0")]
607+
#[inline]
607608
pub fn format(args: Arguments<'_>) -> string::String {
608-
let capacity = args.estimated_capacity();
609-
let mut output = string::String::with_capacity(capacity);
610-
output.write_fmt(args).expect("a formatting trait implementation returned an error");
611-
output
609+
fn format_inner(args: Arguments<'_>) -> string::String {
610+
let capacity = args.estimated_capacity();
611+
let mut output = string::String::with_capacity(capacity);
612+
output.write_fmt(args).expect("a formatting trait implementation returned an error");
613+
output
614+
}
615+
616+
args.as_str().map_or_else(|| format_inner(args), crate::borrow::ToOwned::to_owned)
612617
}

0 commit comments

Comments
 (0)