Skip to content

Commit

Permalink
perf: improve write_fmt to handle simple strings
Browse files Browse the repository at this point in the history
Per @dtolnay suggestion in serde-rs/serde#2697 (comment) - attempt to speed up performance in the cases of a simple string format without arguments:

```rust
write!(f, "text")  ->  f.write_str("text")
```
  • Loading branch information
nyurik committed Feb 13, 2024
1 parent 74c3f5a commit aaed7ab
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions library/core/src/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,14 +201,22 @@ pub trait Write {
impl<W: Write + ?Sized> SpecWriteFmt for &mut W {
#[inline]
default fn spec_write_fmt(mut self, args: Arguments<'_>) -> Result {
write(&mut self, args)
if let Some(s) = args.as_str() {
self.write_str(s)
} else {
write(&mut self, args)
}
}
}

impl<W: Write> SpecWriteFmt for &mut W {
#[inline]
fn spec_write_fmt(self, args: Arguments<'_>) -> Result {
write(self, args)
if let Some(s) = args.as_str() {
self.write_str(s)
} else {
write(self, args)
}
}
}

Expand Down Expand Up @@ -1582,8 +1590,13 @@ impl<'a> Formatter<'a> {
/// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
write(self.buf, fmt)
if let Some(s) = fmt.as_str() {
self.buf.write_str(s)
} else {
write(self.buf, fmt)
}
}

/// Flags for formatting
Expand Down Expand Up @@ -2272,8 +2285,13 @@ impl Write for Formatter<'_> {
self.buf.write_char(c)
}

#[inline]
fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
write(self.buf, args)
if let Some(s) = args.as_str() {
self.buf.write_str(s)
} else {
write(self.buf, args)
}
}
}

Expand Down

0 comments on commit aaed7ab

Please sign in to comment.