Skip to content

Commit 78846d1

Browse files
committed
Specialize fmt::Write::write_fmt for Sized types
1 parent 203c57d commit 78846d1

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

Diff for: library/core/src/fmt/mod.rs

+22-2
Original file line numberDiff line numberDiff line change
@@ -188,8 +188,28 @@ pub trait Write {
188188
/// assert_eq!(&buf, "world");
189189
/// ```
190190
#[stable(feature = "rust1", since = "1.0.0")]
191-
fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
192-
write(&mut self, args)
191+
fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
192+
// We use a specialization for `Sized` types to avoid an indirection
193+
// through `&mut self`
194+
trait SpecWriteFmt {
195+
fn spec_write_fmt(self, args: Arguments<'_>) -> Result;
196+
}
197+
198+
impl<W: Write + ?Sized> SpecWriteFmt for &mut W {
199+
#[inline]
200+
default fn spec_write_fmt(mut self, args: Arguments<'_>) -> Result {
201+
write(&mut self, args)
202+
}
203+
}
204+
205+
impl<W: Write> SpecWriteFmt for &mut W {
206+
#[inline]
207+
fn spec_write_fmt(self, args: Arguments<'_>) -> Result {
208+
write(self, args)
209+
}
210+
}
211+
212+
self.spec_write_fmt(args)
193213
}
194214
}
195215

0 commit comments

Comments
 (0)