binary-size: remove many uses of write!

Using `write!` unnecessarily when a simple `f.write_str` would do ends
up generating more LLVM lines on my Biff `cargo llvm-lines` benchmark.
This PR replaces those uses of `write!` with `Formatter::write_str`.
This commit is contained in:
Andrew Gallant 2025-12-22 14:54:35 -05:00
parent 21f69521cd
commit b78cf711ac
No known key found for this signature in database
GPG key ID: B2E3A4923F8B0D44
14 changed files with 79 additions and 97 deletions

View file

@ -1673,8 +1673,7 @@ impl core::fmt::Display for PosixJulianNoLeapError {
f.write_str("invalid one-based Julian day digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed one-based Julian day, but it's not in supported \
range of `1..=365`",
),
@ -1696,8 +1695,7 @@ impl core::fmt::Display for PosixJulianLeapError {
f.write_str("invalid zero-based Julian day digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed zero-based Julian day, but it's not in supported \
range of `0..=365`",
),
@ -1928,8 +1926,7 @@ impl core::fmt::Display for MonthError {
f.write_str("invalid month digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed month, but it's not in supported \
range of `1..=12`",
),
@ -1951,8 +1948,7 @@ impl core::fmt::Display for WeekOfMonthError {
f.write_str("invalid week-of-month digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed week-of-month, but it's not in supported \
range of `1..=5`",
),
@ -1974,8 +1970,7 @@ impl core::fmt::Display for WeekdayError {
f.write_str("invalid weekday digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed weekday, but it's not in supported \
range of `0..=6` (with `0` corresponding to Sunday)",
),
@ -1997,8 +1992,7 @@ impl core::fmt::Display for HourIanaError {
f.write_str("invalid hour digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed hours, but it's not in supported \
range of `-167..=167`",
),
@ -2020,8 +2014,7 @@ impl core::fmt::Display for HourPosixError {
f.write_str("invalid hour digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed hours, but it's not in supported \
range of `0..=24`",
),
@ -2043,8 +2036,7 @@ impl core::fmt::Display for MinuteError {
f.write_str("invalid minute digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed minutes, but it's not in supported \
range of `0..=59`",
),
@ -2066,8 +2058,7 @@ impl core::fmt::Display for SecondError {
f.write_str("invalid second digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed seconds, but it's not in supported \
range of `0..=59`",
),

View file

@ -248,11 +248,7 @@ impl Numeric {
// `Offset` fails.
impl core::fmt::Display for Numeric {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
if self.sign == C(-1) {
write!(f, "-")?;
} else {
write!(f, "+")?;
}
f.write_str(if self.sign == C(-1) { "-" } else { "+" })?;
write!(f, "{:02}", self.hours)?;
if let Some(minutes) = self.minutes {
write!(f, ":{:02}", minutes)?;
@ -262,11 +258,8 @@ impl core::fmt::Display for Numeric {
}
if let Some(nanos) = self.nanoseconds {
static FMT: FractionalFormatter = FractionalFormatter::new();
write!(
f,
".{}",
FMT.format(i32::from(nanos).unsigned_abs()).as_str()
)?;
f.write_str(".")?;
f.write_str(FMT.format(i32::from(nanos).unsigned_abs()).as_str())?;
}
Ok(())
}

View file

@ -1683,8 +1683,7 @@ impl core::fmt::Display for PosixJulianNoLeapError {
f.write_str("invalid one-based Julian day digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed one-based Julian day, but it's not in supported \
range of `1..=365`",
),
@ -1706,8 +1705,7 @@ impl core::fmt::Display for PosixJulianLeapError {
f.write_str("invalid zero-based Julian day digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed zero-based Julian day, but it's not in supported \
range of `0..=365`",
),
@ -1938,8 +1936,7 @@ impl core::fmt::Display for MonthError {
f.write_str("invalid month digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed month, but it's not in supported \
range of `1..=12`",
),
@ -1961,8 +1958,7 @@ impl core::fmt::Display for WeekOfMonthError {
f.write_str("invalid week-of-month digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed week-of-month, but it's not in supported \
range of `1..=5`",
),
@ -1984,8 +1980,7 @@ impl core::fmt::Display for WeekdayError {
f.write_str("invalid weekday digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed weekday, but it's not in supported \
range of `0..=6` (with `0` corresponding to Sunday)",
),
@ -2007,8 +2002,7 @@ impl core::fmt::Display for HourIanaError {
f.write_str("invalid hour digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed hours, but it's not in supported \
range of `-167..=167`",
),
@ -2030,8 +2024,7 @@ impl core::fmt::Display for HourPosixError {
f.write_str("invalid hour digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed hours, but it's not in supported \
range of `0..=24`",
),
@ -2053,8 +2046,7 @@ impl core::fmt::Display for MinuteError {
f.write_str("invalid minute digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed minutes, but it's not in supported \
range of `0..=59`",
),
@ -2076,8 +2068,7 @@ impl core::fmt::Display for SecondError {
f.write_str("invalid second digits: ")?;
core::fmt::Display::fmt(err, f)
}
Range => write!(
f,
Range => f.write_str(
"parsed seconds, but it's not in supported \
range of `0..=59`",
),

View file

@ -2347,16 +2347,19 @@ impl core::fmt::Debug for SignedDuration {
if f.alternate() {
if self.subsec_nanos() == 0 {
write!(f, "{}s", self.as_secs())
core::fmt::Display::fmt(&self.as_secs(), f)?;
f.write_str("s")
} else if self.as_secs() == 0 {
write!(f, "{}ns", self.subsec_nanos())
core::fmt::Display::fmt(&self.subsec_nanos(), f)?;
f.write_str("ns")
} else {
write!(
core::fmt::Display::fmt(&self.as_secs(), f)?;
f.write_str("s ")?;
core::fmt::Display::fmt(
&self.subsec_nanos().unsigned_abs(),
f,
"{}s {}ns",
self.as_secs(),
self.subsec_nanos().unsigned_abs()
)
)?;
f.write_str("ns")
}
} else {
friendly::DEFAULT_SPAN_PRINTER

View file

@ -3256,7 +3256,7 @@ impl Span {
if self.nanoseconds != C(0) {
write!(buf, ", nanoseconds: {:?}", self.nanoseconds).unwrap();
}
write!(buf, " }}").unwrap();
buf.push_str(" }}");
buf
}

View file

@ -560,16 +560,16 @@ impl TimeZoneDatabase {
impl core::fmt::Debug for TimeZoneDatabase {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "TimeZoneDatabase(")?;
f.write_str("TimeZoneDatabase(")?;
let Some(inner) = self.inner.as_deref() else {
return write!(f, "unavailable)");
return f.write_str("unavailable)");
};
match *inner {
Kind::ZoneInfo(ref db) => write!(f, "{db:?}")?,
Kind::Concatenated(ref db) => write!(f, "{db:?}")?,
Kind::Bundled(ref db) => write!(f, "{db:?}")?,
Kind::ZoneInfo(ref db) => core::fmt::Debug::fmt(db, f)?,
Kind::Concatenated(ref db) => core::fmt::Debug::fmt(db, f)?,
Kind::Bundled(ref db) => core::fmt::Debug::fmt(db, f)?,
}
write!(f, ")")
f.write_str(")")
}
}
@ -675,7 +675,7 @@ impl<'d> TimeZoneName<'d> {
impl<'d> core::fmt::Display for TimeZoneName<'d> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "{}", self.as_str())
f.write_str(self.as_str())
}
}

View file

@ -204,13 +204,13 @@ impl Database {
impl core::fmt::Debug for Database {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "ZoneInfo(")?;
f.write_str("ZoneInfo(")?;
if let Some(ref dir) = self.dir {
write!(f, "{}", dir.display())?;
core::fmt::Display::fmt(&dir.display(), f)?;
} else {
write!(f, "unavailable")?;
f.write_str("unavailable")?;
}
write!(f, ")")
f.write_str(")")
}
}

View file

@ -1110,7 +1110,7 @@ impl core::fmt::Display for Offset {
let minutes = self.part_minutes_ranged().abs().get();
let seconds = self.part_seconds_ranged().abs().get();
if hours == 0 && minutes == 0 && seconds == 0 {
write!(f, "+00")
f.write_str("+00")
} else if hours != 0 && minutes == 0 && seconds == 0 {
write!(f, "{sign}{hours:02}")
} else if minutes != 0 && seconds == 0 {

View file

@ -2269,9 +2269,9 @@ mod repr {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
each! {
self,
UTC => write!(f, "UTC"),
UNKNOWN => write!(f, "Etc/Unknown"),
FIXED(offset) => write!(f, "{offset:?}"),
UTC => f.write_str("UTC"),
UNKNOWN => f.write_str("Etc/Unknown"),
FIXED(offset) => core::fmt::Debug::fmt(&offset, f),
STATIC_TZIF(tzif) => {
// The full debug output is a bit much, so constrain it.
let field = tzif.name().unwrap_or("Local");
@ -2282,7 +2282,11 @@ mod repr {
let field = tzif.name().unwrap_or("Local");
f.debug_tuple("TZif").field(&field).finish()
},
ARC_POSIX(posix) => write!(f, "Posix({posix})"),
ARC_POSIX(posix) => {
f.write_str("Posix(")?;
core::fmt::Display::fmt(&posix, f)?;
f.write_str(")")
},
}
}
}

View file

@ -570,9 +570,9 @@ impl shared::TzifLocalTimeType {
impl core::fmt::Display for shared::TzifIndicator {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match *self {
shared::TzifIndicator::LocalWall => write!(f, "local/wall"),
shared::TzifIndicator::LocalStandard => write!(f, "local/std"),
shared::TzifIndicator::UTStandard => write!(f, "ut/std"),
shared::TzifIndicator::LocalWall => f.write_str("local/wall"),
shared::TzifIndicator::LocalStandard => f.write_str("local/std"),
shared::TzifIndicator::UTStandard => f.write_str("ut/std"),
}
}
}

View file

@ -49,7 +49,7 @@ impl Sign {
impl core::fmt::Display for Sign {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
if self.is_negative() {
write!(f, "-")
f.write_str("-")
} else {
Ok(())
}

View file

@ -36,15 +36,13 @@ impl Expiration {
impl core::fmt::Display for Expiration {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let Some(instant) = self.0 else {
return write!(f, "expired");
};
let Some(now) = crate::now::monotonic_time() else {
return write!(f, "expired");
};
let Some(duration) = instant.checked_duration_since(now) else {
return write!(f, "expired");
};
write!(f, "{duration:?}")
let maybe_duration = self.0.and_then(|instant| {
crate::now::monotonic_time()
.and_then(|now| instant.checked_duration_since(now))
});
match maybe_duration {
None => f.write_str("expired"),
Some(duration) => core::fmt::Debug::fmt(&duration, f),
}
}
}

View file

@ -18,7 +18,7 @@ impl core::fmt::Display for Byte {
#[inline(never)]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
if self.0 == b' ' {
return write!(f, " ");
return f.write_str(" ");
}
// 10 bytes is enough for any output from ascii::escape_default.
let mut bytes = [0u8; 10];
@ -31,16 +31,16 @@ impl core::fmt::Display for Byte {
bytes[len] = b;
len += 1;
}
write!(f, "{}", core::str::from_utf8(&bytes[..len]).unwrap())
f.write_str(core::str::from_utf8(&bytes[..len]).unwrap())
}
}
impl core::fmt::Debug for Byte {
#[inline(never)]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "\"")?;
f.write_str("\"")?;
core::fmt::Display::fmt(self, f)?;
write!(f, "\"")?;
f.write_str("\"")?;
Ok(())
}
}
@ -70,11 +70,13 @@ impl<'a> core::fmt::Display for Bytes<'a> {
};
bytes = &bytes[ch.len_utf8()..];
match ch {
'\0' => write!(f, "\\0")?,
'\0' => f.write_str(r"\0")?,
'\x01'..='\x7f' => {
write!(f, "{}", (ch as u8).escape_ascii())?;
core::fmt::Display::fmt(&(ch as u8).escape_ascii(), f)?;
}
_ => {
core::fmt::Display::fmt(&ch.escape_debug(), f)?;
}
_ => write!(f, "{}", ch.escape_debug())?,
}
}
Ok(())
@ -84,9 +86,9 @@ impl<'a> core::fmt::Display for Bytes<'a> {
impl<'a> core::fmt::Debug for Bytes<'a> {
#[inline(never)]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "\"")?;
f.write_str("\"")?;
core::fmt::Display::fmt(self, f)?;
write!(f, "\"")?;
f.write_str("\"")?;
Ok(())
}
}
@ -105,7 +107,7 @@ impl core::fmt::Display for RepeatByte {
#[inline(never)]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
for _ in 0..self.count {
write!(f, "{}", Byte(self.byte))?;
core::fmt::Display::fmt(&Byte(self.byte), f)?;
}
Ok(())
}
@ -114,9 +116,9 @@ impl core::fmt::Display for RepeatByte {
impl core::fmt::Debug for RepeatByte {
#[inline(never)]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "\"")?;
f.write_str("\"")?;
core::fmt::Display::fmt(self, f)?;
write!(f, "\"")?;
f.write_str("\"")?;
Ok(())
}
}

View file

@ -2093,7 +2093,7 @@ macro_rules! define_ranged {
// its debug repr which should show some nice output.
match self.checked_add(Self::N::<0>()) {
Some(val) => core::fmt::Display::fmt(&val.get(), f),
None => write!(f, "{:?}", self),
None => core::fmt::Debug::fmt(self, f),
}
}
}