Skip to content

Optimize ToString implementation for integers #136264

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2824,7 +2824,54 @@ impl SpecToString for bool {
}
}

macro_rules! impl_to_string {
($($signed:ident, $unsigned:ident,)*) => {
$(
#[cfg(not(no_global_oom_handling))]
#[cfg(not(feature = "optimize_for_size"))]
impl SpecToString for $signed {
#[inline]
fn spec_to_string(&self) -> String {
const SIZE: usize = $signed::MAX.ilog(10) as usize + 1;
let mut buf = [core::mem::MaybeUninit::<u8>::uninit(); SIZE];
// Only difference between signed and unsigned are these 8 lines.
let mut out;
if *self < 0 {
out = String::with_capacity(SIZE + 1);
out.push('-');
} else {
out = String::with_capacity(SIZE);
}

out.push_str(self.unsigned_abs()._fmt(&mut buf));
out
}
}
#[cfg(not(no_global_oom_handling))]
#[cfg(not(feature = "optimize_for_size"))]
impl SpecToString for $unsigned {
#[inline]
fn spec_to_string(&self) -> String {
const SIZE: usize = $unsigned::MAX.ilog(10) as usize + 1;
let mut buf = [core::mem::MaybeUninit::<u8>::uninit(); SIZE];

self._fmt(&mut buf).to_string()
}
}
)*
}
}

impl_to_string! {
i8, u8,
i16, u16,
i32, u32,
i64, u64,
isize, usize,
}

#[cfg(not(no_global_oom_handling))]
#[cfg(feature = "optimize_for_size")]
impl SpecToString for u8 {
#[inline]
fn spec_to_string(&self) -> String {
Expand All @@ -2844,6 +2891,7 @@ impl SpecToString for u8 {
}

#[cfg(not(no_global_oom_handling))]
#[cfg(feature = "optimize_for_size")]
impl SpecToString for i8 {
#[inline]
fn spec_to_string(&self) -> String {
Expand Down
28 changes: 19 additions & 9 deletions library/core/src/fmt/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,11 @@ macro_rules! impl_Display {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[cfg(not(feature = "optimize_for_size"))]
{
self._fmt(true, f)
const MAX_DEC_N: usize = $unsigned::MAX.ilog(10) as usize + 1;
// Buffer decimals for $unsigned with right alignment.
let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];

f.pad_integral(true, "", self._fmt(&mut buf))
}
#[cfg(feature = "optimize_for_size")]
{
Expand All @@ -222,7 +226,11 @@ macro_rules! impl_Display {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[cfg(not(feature = "optimize_for_size"))]
{
return self.unsigned_abs()._fmt(*self >= 0, f);
const MAX_DEC_N: usize = $unsigned::MAX.ilog(10) as usize + 1;
// Buffer decimals for $unsigned with right alignment.
let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];

f.pad_integral(*self >= 0, "", self.unsigned_abs()._fmt(&mut buf))
}
#[cfg(feature = "optimize_for_size")]
{
Expand All @@ -233,10 +241,13 @@ macro_rules! impl_Display {

#[cfg(not(feature = "optimize_for_size"))]
impl $unsigned {
fn _fmt(self, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result {
const MAX_DEC_N: usize = $unsigned::MAX.ilog(10) as usize + 1;
// Buffer decimals for $unsigned with right alignment.
let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];
#[doc(hidden)]
#[unstable(
feature = "fmt_internals",
reason = "specialized method meant to only be used by `SpecToString` implementation",
issue = "none"
)]
pub fn _fmt<'a>(self, buf: &'a mut [MaybeUninit::<u8>]) -> &'a str {
// Count the number of bytes in buf that are not initialized.
let mut offset = buf.len();
// Consume the least-significant decimals from a working copy.
Expand Down Expand Up @@ -301,13 +312,12 @@ macro_rules! impl_Display {
// SAFETY: All buf content since offset is set.
let written = unsafe { buf.get_unchecked(offset..) };
// SAFETY: Writes use ASCII from the lookup table exclusively.
let as_str = unsafe {
unsafe {
str::from_utf8_unchecked(slice::from_raw_parts(
MaybeUninit::slice_as_ptr(written),
written.len(),
))
};
f.pad_integral(is_nonnegative, "", as_str)
}
}
})*

Expand Down
2 changes: 1 addition & 1 deletion tests/ui/codegen/equal-pointers-unequal/as-cast/inline2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn main() {
let v = 0;
&v as *const _ as usize
};
assert_eq!(a.to_string(), b.to_string());
assert_eq!(format!("{a}"), format!("{b}"));
assert_eq!(format!("{}", a == b), "true");
assert_eq!(format!("{}", cmp_in(a, b)), "true");
assert_eq!(format!("{}", cmp(a, b)), "true");
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/codegen/equal-pointers-unequal/as-cast/zero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ fn main() {
// It's not zero, which means `a` and `b` are not equal.
assert_ne!(i, 0);
// But it looks like zero...
assert_eq!(i.to_string(), "0");
assert_eq!(format!("{i}"), "0");
// ...and now it *is* zero?
assert_eq!(i, 0);
// So `a` and `b` are equal after all?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fn main() {
let v = 0;
ptr::from_ref(&v).expose_provenance()
};
assert_eq!(a.to_string(), b.to_string());
assert_eq!(format!("{a}"), format!("{b}"));
assert_eq!(format!("{}", a == b), "true");
assert_eq!(format!("{}", cmp_in(a, b)), "true");
assert_eq!(format!("{}", cmp(a, b)), "true");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn main() {
// It's not zero, which means `a` and `b` are not equal.
assert_ne!(i, 0);
// But it looks like zero...
assert_eq!(i.to_string(), "0");
assert_eq!(format!("{i}"), "0");
// ...and now it *is* zero?
assert_eq!(i, 0);
// So `a` and `b` are equal after all?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fn main() {
let v = 0;
ptr::from_ref(&v).addr()
};
assert_eq!(a.to_string(), b.to_string());
assert_eq!(format!("{a}"), format!("{b}"));
assert_eq!(format!("{}", a == b), "true");
assert_eq!(format!("{}", cmp_in(a, b)), "true");
assert_eq!(format!("{}", cmp(a, b)), "true");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn main() {
// It's not zero, which means `a` and `b` are not equal.
assert_ne!(i, 0);
// But it looks like zero...
assert_eq!(i.to_string(), "0");
assert_eq!(format!("{i}"), "0");
// ...and now it *is* zero?
assert_eq!(i, 0);
// So `a` and `b` are equal after all?
Expand Down
Loading