diff options
| author | Guillaume Gomez <guillaume1.gomez@gmail.com> | 2025-01-29 22:22:56 +0100 |
|---|---|---|
| committer | Guillaume Gomez <guillaume1.gomez@gmail.com> | 2025-04-12 20:58:14 +0200 |
| commit | 25f17dd8254588300f7bc431d586f3b7c4ee2df1 (patch) | |
| tree | aeebb215cb59e72f7d393cca20fab3d28200cff9 /library/alloc/src | |
| parent | 7d7de5bf3c3cbf9c2c5bbc5cbfb9197a8a427d35 (diff) | |
Optimize `ToString` implementation for integers
Diffstat (limited to 'library/alloc/src')
| -rw-r--r-- | library/alloc/src/string.rs | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 9a161d057db..1a0b3b43eb6 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -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 { @@ -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 { |
