diff options
| author | bors <bors@rust-lang.org> | 2022-05-30 17:39:58 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2022-05-30 17:39:58 +0000 |
| commit | 4a8d2e3856c0c75c71998b6c85937203839b946d (patch) | |
| tree | 68c4e985080db02c2bfbe9e337fd37814ba94e8c | |
| parent | e810f750a2a407f9caeabba39059578e844add14 (diff) | |
| parent | 5dd0fe301ac0180afddc12ad3124ab0a1f813298 (diff) | |
| download | rust-4a8d2e3856c0c75c71998b6c85937203839b946d.tar.gz rust-4a8d2e3856c0c75c71998b6c85937203839b946d.zip | |
Auto merge of #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 (https://github.com/rust-lang/rfcs/pull/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
| -rw-r--r-- | library/alloc/src/fmt.rs | 13 |
1 files changed, 9 insertions, 4 deletions
diff --git a/library/alloc/src/fmt.rs b/library/alloc/src/fmt.rs index 73b75ea4d83..ed398b56612 100644 --- a/library/alloc/src/fmt.rs +++ b/library/alloc/src/fmt.rs @@ -604,9 +604,14 @@ use crate::string; #[cfg(not(no_global_oom_handling))] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] +#[inline] pub fn format(args: Arguments<'_>) -> string::String { - let capacity = args.estimated_capacity(); - let mut output = string::String::with_capacity(capacity); - output.write_fmt(args).expect("a formatting trait implementation returned an error"); - output + fn format_inner(args: Arguments<'_>) -> string::String { + let capacity = args.estimated_capacity(); + let mut output = string::String::with_capacity(capacity); + output.write_fmt(args).expect("a formatting trait implementation returned an error"); + output + } + + args.as_str().map_or_else(|| format_inner(args), crate::borrow::ToOwned::to_owned) } |
