Skip to content

Commit 167798e

Browse files
committed
Reserve before fmt::Write::write_fmt
1 parent 3127f86 commit 167798e

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

library/alloc/src/string.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3186,6 +3186,15 @@ impl fmt::Write for String {
31863186
self.push(c);
31873187
Ok(())
31883188
}
3189+
3190+
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
3191+
if let Some(s) = args.as_statically_known_str() {
3192+
self.write_str(s)
3193+
} else {
3194+
self.reserve(args.estimated_capacity());
3195+
fmt::write(self, args)
3196+
}
3197+
}
31893198
}
31903199

31913200
/// An iterator over the [`char`]s of a string.

library/core/src/fmt/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -710,9 +710,10 @@ impl<'a> Arguments<'a> {
710710
}
711711

712712
/// Same as [`Arguments::as_str`], but will only return `Some(s)` if it can be determined at compile time.
713+
#[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
713714
#[must_use]
714715
#[inline]
715-
fn as_statically_known_str(&self) -> Option<&'static str> {
716+
pub fn as_statically_known_str(&self) -> Option<&'static str> {
716717
let s = self.as_str();
717718
if core::intrinsics::is_val_statically_known(s.is_some()) { s } else { None }
718719
}

library/std/src/ffi/os_str.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -753,10 +753,20 @@ impl Hash for OsString {
753753

754754
#[stable(feature = "os_string_fmt_write", since = "1.64.0")]
755755
impl fmt::Write for OsString {
756+
#[inline]
756757
fn write_str(&mut self, s: &str) -> fmt::Result {
757758
self.push(s);
758759
Ok(())
759760
}
761+
762+
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
763+
if let Some(s) = args.as_statically_known_str() {
764+
self.write_str(s)
765+
} else {
766+
self.reserve(args.estimated_capacity());
767+
fmt::write(self, args)
768+
}
769+
}
760770
}
761771

762772
impl OsStr {

0 commit comments

Comments
 (0)