Skip to content

Commit e0cc6ac

Browse files
Specialize format! with pattern-matching
If the first argument to format! is "{}" then the rest of the args must be something that implements fmt::Display and thus ToString. We can thus call ToString on it. In order to type-safely eat all those arguments, a struct wrapper inside a closure prevents misuse.
1 parent c336478 commit e0cc6ac

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

library/alloc/src/macros.rs

+12
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,18 @@ macro_rules! vec {
102102
#[macro_export]
103103
#[stable(feature = "rust1", since = "1.0.0")]
104104
macro_rules! format {
105+
// A faster path for simple format! calls.
106+
("{}", $($arg:tt,?)+) => {{
107+
// It is possible to implement ToString manually, bypassing Display.
108+
// However, "{}" formats in terms of Display. This wrapper enforces
109+
// equally strict type boundaries even though we are calling ToString.
110+
struct NeedsDisplay<T: $crate::fmt::Display> {
111+
inner: T,
112+
}
113+
let fast = |t: NeedsDisplay<_> | $crate::string::ToString::to_string(t.inner);
114+
// This TokenTree must resolve to a Displayable value to be valid.
115+
fast(NeedsDisplay { inner: &{$($arg)*} })
116+
}};
105117
($($arg:tt)*) => {{
106118
let res = $crate::fmt::format($crate::__export::format_args!($($arg)*));
107119
res

0 commit comments

Comments
 (0)