Skip to content

Commit d8b6fe8

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

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

library/alloc/src/string.rs

+10
Original file line numberDiff line numberDiff line change
@@ -3186,6 +3186,16 @@ impl fmt::Write for String {
31863186
self.push(c);
31873187
Ok(())
31883188
}
3189+
3190+
#[inline]
3191+
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
3192+
if let Some(s) = args.as_statically_known_str() {
3193+
self.write_str(s)
3194+
} else {
3195+
self.reserve(args.estimated_capacity());
3196+
fmt::write(self, args)
3197+
}
3198+
}
31893199
}
31903200

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

library/core/src/fmt/mod.rs

+2-1
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

+11
Original file line numberDiff line numberDiff line change
@@ -753,10 +753,21 @@ 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+
#[inline]
763+
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
764+
if let Some(s) = args.as_statically_known_str() {
765+
self.write_str(s)
766+
} else {
767+
self.reserve(args.estimated_capacity());
768+
fmt::write(self, args)
769+
}
770+
}
760771
}
761772

762773
impl OsStr {

0 commit comments

Comments
 (0)