Skip to content

Commit

Permalink
Auto merge of #97480 - conradludgate:faster-format-literals, r=joshtr…
Browse files Browse the repository at this point in the history
…iplett

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
  • Loading branch information
bors committed May 30, 2022
2 parents e58c4ee + c96cb67 commit 6d12d2e
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions alloc/src/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 6d12d2e

Please sign in to comment.