Skip to content

Commit b86d755

Browse files
committed
Optimize io::Write::write_fmt for constant strings
When the formatting args to `fmt::Write::write_fmt` are a statically known string, it simplifies to only calling `write_str` without a runtime branch. Do the same in `io::Write::write_fmt` with `write_all`. Also, match the convention of `fmt::Write` for the name of `args`.
1 parent 8caa2f9 commit b86d755

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

library/std/src/io/mod.rs

+8-4
Original file line numberDiff line numberDiff line change
@@ -614,7 +614,7 @@ pub(crate) fn default_read_buf_exact<R: Read + ?Sized>(
614614

615615
pub(crate) fn default_write_fmt<W: Write + ?Sized>(
616616
this: &mut W,
617-
fmt: fmt::Arguments<'_>,
617+
args: fmt::Arguments<'_>,
618618
) -> Result<()> {
619619
// Create a shim which translates a `Write` to a `fmt::Write` and saves off
620620
// I/O errors, instead of discarding them.
@@ -636,7 +636,7 @@ pub(crate) fn default_write_fmt<W: Write + ?Sized>(
636636
}
637637

638638
let mut output = Adapter { inner: this, error: Ok(()) };
639-
match fmt::write(&mut output, fmt) {
639+
match fmt::write(&mut output, args) {
640640
Ok(()) => Ok(()),
641641
Err(..) => {
642642
// Check whether the error came from the underlying `Write`.
@@ -1907,8 +1907,12 @@ pub trait Write {
19071907
/// }
19081908
/// ```
19091909
#[stable(feature = "rust1", since = "1.0.0")]
1910-
fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1911-
default_write_fmt(self, fmt)
1910+
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<()> {
1911+
if let Some(s) = args.as_statically_known_str() {
1912+
self.write_all(s.as_bytes())
1913+
} else {
1914+
default_write_fmt(self, args)
1915+
}
19121916
}
19131917

19141918
/// Creates a "by reference" adapter for this instance of `Write`.

0 commit comments

Comments
 (0)