Skip to main content

core/fmt/
num.rs

1//! Integer and floating-point number formatting
2
3use crate::fmt::NumBuffer;
4use crate::mem::MaybeUninit;
5use crate::num::imp::fmt as numfmt;
6use crate::{fmt, str};
7
8/// Formatting of integers with a non-decimal radix.
9macro_rules! radix_integer {
10    (fmt::$Trait:ident for $Signed:ident and $Unsigned:ident, $prefix:literal, $dig_tab:literal) => {
11        #[stable(feature = "rust1", since = "1.0.0")]
12        impl fmt::$Trait for $Unsigned {
13            /// Format unsigned integers in the radix.
14            #[ferrocene::prevalidated]
15            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16                // Check macro arguments at compile time.
17                const {
18                    assert!($Unsigned::MIN == 0, "need unsigned");
19                    assert!($dig_tab.is_ascii(), "need single-byte entries");
20                }
21
22                // ASCII digits in ascending order are used as a lookup table.
23                const DIG_TAB: &[u8] = $dig_tab;
24                const BASE: $Unsigned = DIG_TAB.len() as $Unsigned;
25                const MAX_DIG_N: usize = $Unsigned::MAX.ilog(BASE) as usize + 1;
26
27                // Buffer digits of self with right alignment.
28                let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DIG_N];
29                // Count the number of bytes in buf that are not initialized.
30                let mut offset = buf.len();
31
32                // Accumulate each digit of the number from the least
33                // significant to the most significant figure.
34                let mut remain = *self;
35                loop {
36                    let digit = remain % BASE;
37                    remain /= BASE;
38
39                    offset -= 1;
40                    // SAFETY: `remain` will reach 0 and we will break before `offset` wraps
41                    unsafe { core::hint::assert_unchecked(offset < buf.len()) }
42                    buf[offset].write(DIG_TAB[digit as usize]);
43                    if remain == 0 {
44                        break;
45                    }
46                }
47
48                // SAFETY: Starting from `offset`, all elements of the slice have been set.
49                let digits = unsafe { slice_buffer_to_str(&buf, offset) };
50                f.pad_integral(true, $prefix, digits)
51            }
52        }
53
54        #[stable(feature = "rust1", since = "1.0.0")]
55        impl fmt::$Trait for $Signed {
56            /// Format signed integers in the two’s-complement form.
57            #[ferrocene::prevalidated]
58            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59                fmt::$Trait::fmt(&self.cast_unsigned(), f)
60            }
61        }
62    };
63}
64
65/// Formatting of integers with a non-decimal radix.
66macro_rules! radix_integers {
67    ($Signed:ident, $Unsigned:ident) => {
68        radix_integer! { fmt::Binary   for $Signed and $Unsigned, "0b", b"01" }
69        radix_integer! { fmt::Octal    for $Signed and $Unsigned, "0o", b"01234567" }
70        radix_integer! { fmt::LowerHex for $Signed and $Unsigned, "0x", b"0123456789abcdef" }
71        radix_integer! { fmt::UpperHex for $Signed and $Unsigned, "0x", b"0123456789ABCDEF" }
72    };
73}
74radix_integers! { isize, usize }
75radix_integers! { i8, u8 }
76radix_integers! { i16, u16 }
77radix_integers! { i32, u32 }
78radix_integers! { i64, u64 }
79radix_integers! { i128, u128 }
80
81macro_rules! impl_Debug {
82    ($($T:ident)*) => {
83        $(
84            #[stable(feature = "rust1", since = "1.0.0")]
85            impl fmt::Debug for $T {
86                #[inline]
87                #[ferrocene::prevalidated]
88                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89                    if f.debug_lower_hex() {
90                        fmt::LowerHex::fmt(self, f)
91                    } else if f.debug_upper_hex() {
92                        fmt::UpperHex::fmt(self, f)
93                    } else {
94                        fmt::Display::fmt(self, f)
95                    }
96                }
97            }
98        )*
99    };
100}
101
102// The string of all two-digit numbers in range 00..99 is used as a lookup table.
103static DECIMAL_PAIRS: &[u8; 200] = b"\
104      0001020304050607080910111213141516171819\
105      2021222324252627282930313233343536373839\
106      4041424344454647484950515253545556575859\
107      6061626364656667686970717273747576777879\
108      8081828384858687888990919293949596979899";
109
110/// This function converts a slice of ascii characters into a `&str` starting from `offset`.
111///
112/// # Safety
113///
114/// `buf` content starting from `offset` index MUST BE initialized and MUST BE ascii
115/// characters.
116#[ferrocene::prevalidated]
117unsafe fn slice_buffer_to_str(buf: &[MaybeUninit<u8>], offset: usize) -> &str {
118    // SAFETY: `offset` is always included between 0 and `buf`'s length.
119    let written = unsafe { buf.get_unchecked(offset..) };
120    // SAFETY: (`assume_init_ref`) All buf content since offset is set.
121    // SAFETY: (`from_utf8_unchecked`) Writes use ASCII from the lookup table exclusively.
122    unsafe { str::from_utf8_unchecked(written.assume_init_ref()) }
123}
124
125macro_rules! impl_Display {
126    ($($Signed:ident, $Unsigned:ident),* ; as $T:ident into $fmt_fn:ident) => {
127
128        $(
129        const _: () = {
130            assert!($Signed::MIN < 0, "need signed");
131            assert!($Unsigned::MIN == 0, "need unsigned");
132            assert!($Signed::BITS == $Unsigned::BITS, "need counterparts");
133            assert!($Signed::BITS <= $T::BITS, "need lossless conversion");
134            assert!($Unsigned::BITS <= $T::BITS, "need lossless conversion");
135        };
136
137        #[stable(feature = "rust1", since = "1.0.0")]
138        impl fmt::Display for $Unsigned {
139            #[ferrocene::prevalidated]
140            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141                #[cfg(not(feature = "optimize_for_size"))]
142                {
143                    const MAX_DEC_N: usize = $Unsigned::MAX.ilog10() as usize + 1;
144                    // Buffer decimals for self with right alignment.
145                    let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];
146
147                    // SAFETY: `buf` is always big enough to contain all the digits.
148                    unsafe { f.pad_integral(true, "", self._fmt(&mut buf)) }
149                }
150                #[cfg(feature = "optimize_for_size")]
151                {
152                    // Lossless conversion (with as) is asserted at the top of
153                    // this macro.
154                    ${concat($fmt_fn, _small)}(*self as $T, true, f)
155                }
156            }
157        }
158
159        #[stable(feature = "rust1", since = "1.0.0")]
160        impl fmt::Display for $Signed {
161            #[ferrocene::prevalidated]
162            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163                #[cfg(not(feature = "optimize_for_size"))]
164                {
165                    const MAX_DEC_N: usize = $Unsigned::MAX.ilog10() as usize + 1;
166                    // Buffer decimals for self with right alignment.
167                    let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];
168
169                    // SAFETY: `buf` is always big enough to contain all the digits.
170                    unsafe { f.pad_integral(*self >= 0, "", self.unsigned_abs()._fmt(&mut buf)) }
171                }
172                #[cfg(feature = "optimize_for_size")]
173                {
174                    // Lossless conversion (with as) is asserted at the top of
175                    // this macro.
176                    return ${concat($fmt_fn, _small)}(self.unsigned_abs() as $T, *self >= 0, f);
177                }
178            }
179        }
180
181        #[cfg(not(feature = "optimize_for_size"))]
182        impl $Unsigned {
183            #[doc(hidden)]
184            #[unstable(
185                feature = "fmt_internals",
186                reason = "specialized method meant to only be used by `SpecToString` implementation",
187                issue = "none"
188            )]
189            #[ferrocene::prevalidated]
190            pub unsafe fn _fmt<'a>(self, buf: &'a mut [MaybeUninit::<u8>]) -> &'a str {
191                // SAFETY: `buf` will always be big enough to contain all digits.
192                let offset = unsafe { self._fmt_inner(buf) };
193                // SAFETY: Starting from `offset`, all elements of the slice have been set.
194                unsafe { slice_buffer_to_str(buf, offset) }
195            }
196
197            #[ferrocene::prevalidated]
198            unsafe fn _fmt_inner(self, buf: &mut [MaybeUninit::<u8>]) -> usize {
199                // Count the number of bytes in buf that are not initialized.
200                let mut offset = buf.len();
201                // Consume the least-significant decimals from a working copy.
202                let mut remain = self;
203
204                // Format per four digits from the lookup table.
205                // Four digits need a 16-bit $Unsigned or wider.
206                while size_of::<Self>() > 1 && remain > 999.try_into().expect("branch is not hit for types that cannot fit 999 (u8)") {
207                    // SAFETY: All of the decimals fit in buf due to MAX_DEC_N
208                    // and the while condition ensures at least 4 more decimals.
209                    unsafe { core::hint::assert_unchecked(offset >= 4) }
210                    // SAFETY: The offset counts down from its initial buf.len()
211                    // without underflow due to the previous precondition.
212                    unsafe { core::hint::assert_unchecked(offset <= buf.len()) }
213                    offset -= 4;
214
215                    // pull two pairs
216                    let scale: Self = 1_00_00.try_into().expect("branch is not hit for types that cannot fit 1E4 (u8)");
217                    let quad = remain % scale;
218                    remain /= scale;
219                    let pair1 = (quad / 100) as usize;
220                    let pair2 = (quad % 100) as usize;
221                    buf[offset + 0].write(DECIMAL_PAIRS[pair1 * 2 + 0]);
222                    buf[offset + 1].write(DECIMAL_PAIRS[pair1 * 2 + 1]);
223                    buf[offset + 2].write(DECIMAL_PAIRS[pair2 * 2 + 0]);
224                    buf[offset + 3].write(DECIMAL_PAIRS[pair2 * 2 + 1]);
225                }
226
227                // Format per two digits from the lookup table.
228                if remain > 9 {
229                    // SAFETY: All of the decimals fit in buf due to MAX_DEC_N
230                    // and the if condition ensures at least 2 more decimals.
231                    unsafe { core::hint::assert_unchecked(offset >= 2) }
232                    // SAFETY: The offset counts down from its initial buf.len()
233                    // without underflow due to the previous precondition.
234                    unsafe { core::hint::assert_unchecked(offset <= buf.len()) }
235                    offset -= 2;
236
237                    let pair = (remain % 100) as usize;
238                    remain /= 100;
239                    buf[offset + 0].write(DECIMAL_PAIRS[pair * 2 + 0]);
240                    buf[offset + 1].write(DECIMAL_PAIRS[pair * 2 + 1]);
241                }
242
243                // Format the last remaining digit, if any.
244                if remain != 0 || self == 0 {
245                    // SAFETY: All of the decimals fit in buf due to MAX_DEC_N
246                    // and the if condition ensures (at least) 1 more decimals.
247                    unsafe { core::hint::assert_unchecked(offset >= 1) }
248                    // SAFETY: The offset counts down from its initial buf.len()
249                    // without underflow due to the previous precondition.
250                    unsafe { core::hint::assert_unchecked(offset <= buf.len()) }
251                    offset -= 1;
252
253                    // Either the compiler sees that remain < 10, or it prevents
254                    // a boundary check up next.
255                    let last = (remain & 15) as usize;
256                    buf[offset].write(DECIMAL_PAIRS[last * 2 + 1]);
257                    // not used: remain = 0;
258                }
259
260                offset
261            }
262        }
263
264        impl $Signed {
265            /// Formats this integer as a signed decimal number, using the memory pointed to by
266            /// `buf` as storage for the returned string slice.
267            ///
268            /// This method can be used to convert integers to strings without involving the
269            /// dynamic dispatch that using [`Display`][fmt::Display] would.
270            /// This may be more efficient in situations where [`fmt`] is not otherwise used.
271            ///
272            /// # Examples
273            ///
274            /// ```
275            /// use core::fmt::NumBuffer;
276            ///
277            #[doc = concat!("let n = 0", stringify!($Signed), ";")]
278            /// let mut buf = NumBuffer::new();
279            /// assert_eq!(n.format_into(&mut buf), "0");
280            ///
281            #[doc = concat!("let n1 = 32", stringify!($Signed), ";")]
282            /// assert_eq!(n1.format_into(&mut buf), "32");
283            ///
284            #[doc = concat!("let n2 = ", stringify!($Signed), "::MAX;")]
285            #[doc = concat!("assert_eq!(n2.format_into(&mut buf), ", stringify!($Signed), "::MAX.to_string());")]
286            /// ```
287            #[ferrocene::prevalidated]
288            #[stable(feature = "int_format_into", since = "1.98.0")]
289            pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
290                let mut offset;
291
292                #[cfg(not(feature = "optimize_for_size"))]
293                // SAFETY: `buf` is from a `NumBuffer`, so it will always be big enough to contain all digits.
294                unsafe {
295                    offset = self.unsigned_abs()._fmt_inner(&mut buf.buf);
296                }
297                #[cfg(feature = "optimize_for_size")]
298                {
299                    // Lossless conversion (with as) is asserted at the top of
300                    // this macro.
301                    // SAFETY: `buf` is from a `NumBuffer`, so it will always be big enough to contain all digits.
302                    offset = unsafe { ${concat($fmt_fn, _in_buf_small)}(self.unsigned_abs() as $T, &mut buf.buf) };
303                }
304                // Only difference between signed and unsigned are these 4 lines.
305                if self < 0 {
306                    offset -= 1;
307                    buf.buf[offset].write(b'-');
308                }
309                // SAFETY: Starting from `offset`, all elements of the slice have been set.
310                unsafe { slice_buffer_to_str(&buf.buf, offset) }
311            }
312        }
313
314        impl $Unsigned {
315            /// Formats this integer as an unsigned decimal number, using the memory pointed to by
316            /// `buf` as storage for the returned string slice.
317            ///
318            /// This method can be used to convert integers to strings without involving the
319            /// dynamic dispatch that using [`Display`][fmt::Display] would.
320            /// This may be more efficient in situations where [`fmt`] is not otherwise used.
321            ///
322            /// # Examples
323            ///
324            /// ```
325            /// use core::fmt::NumBuffer;
326            ///
327            #[doc = concat!("let n = 0", stringify!($Unsigned), ";")]
328            /// let mut buf = NumBuffer::new();
329            /// assert_eq!(n.format_into(&mut buf), "0");
330            ///
331            #[doc = concat!("let n1 = 32", stringify!($Unsigned), ";")]
332            /// assert_eq!(n1.format_into(&mut buf), "32");
333            ///
334            #[doc = concat!("let n2 = ", stringify!($Unsigned::MAX), ";")]
335            #[doc = concat!("assert_eq!(n2.format_into(&mut buf), ", stringify!($Unsigned::MAX), ".to_string());")]
336            /// ```
337            #[ferrocene::prevalidated]
338            #[stable(feature = "int_format_into", since = "1.98.0")]
339            pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
340                let offset;
341
342                #[cfg(not(feature = "optimize_for_size"))]
343                // SAFETY: `buf` is from a `NumBuffer`, so it will always be big enough to contain all digits.
344                unsafe {
345                    offset = self._fmt_inner(&mut buf.buf);
346                }
347                #[cfg(feature = "optimize_for_size")]
348                {
349                    // Lossless conversion (with as) is asserted at the top of
350                    // this macro.
351                    // SAFETY: `buf` is from a `NumBuffer`, so it will always be big enough to contain all digits.
352                    offset = unsafe { ${concat($fmt_fn, _in_buf_small)}(self as $T, &mut buf.buf) };
353                }
354                // SAFETY: Starting from `offset`, all elements of the slice have been set.
355                unsafe { slice_buffer_to_str(&buf.buf, offset) }
356            }
357        }
358
359        )*
360
361        /// # Safety
362        /// The number's decimal representation must fit into the buffer.
363        /// i.e. `n == 0 && buf.len() >= 1 || n.ilog10() + 1 <= buf.len()`
364        ///
365        /// Note that this function is shared across sizes. In particular, `u8` and `u16` use the
366        /// `u32` version of this function, so the buffer length is not always the same; this
367        /// prevents the function from being safe, and/or using `NumBuffer`.
368        #[cfg(feature = "optimize_for_size")]
369        unsafe fn ${concat($fmt_fn, _in_buf_small)}(mut n: $T, buf: &mut [MaybeUninit::<u8>]) -> usize {
370            debug_assert!(n == 0 && buf.len() >= 1 || buf.len() >= n.ilog10() as usize + 1);
371
372            let mut curr = buf.len();
373
374            // SAFETY:
375            // For `n == 0`, we only access index 0, and `buf.len() >= 1`.
376            // Otherwise, it takes `n.ilog10() + 1` divisions by 10 for `n`
377            // to become 0. Hence `curr` is decremented at most that many times.
378            // Then due to `buf.len() >= n.ilog10() + 1`, `curr` can never
379            // wrap, which means it is in-bounds (since it starts in-bounds
380            // and counts down).
381            unsafe {
382                loop {
383                    curr -= 1;
384                    buf.get_unchecked_mut(curr).write((n % 10) as u8 + b'0');
385                    n /= 10;
386
387                    if n == 0 {
388                        break;
389                    }
390                }
391            }
392            curr
393        }
394
395        #[cfg(feature = "optimize_for_size")]
396        fn ${concat($fmt_fn, _small)}(n: $T, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397            const MAX_DEC_N: usize = $T::MAX.ilog10() as usize + 1;
398            let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];
399
400            // SAFETY: `T::MAX` is the largest possible decimal length, so the buffer is large enough.
401            let offset = unsafe { ${concat($fmt_fn, _in_buf_small)}(n, &mut buf) };
402            // SAFETY: Starting from `offset`, all elements of the slice have been set.
403            let buf_slice = unsafe { slice_buffer_to_str(&buf, offset) };
404            f.pad_integral(is_nonnegative, "", buf_slice)
405        }
406    };
407}
408
409macro_rules! impl_Exp {
410    ($($Signed:ident, $Unsigned:ident),* ; as $T:ident into $fmt_fn:ident) => {
411        const _: () = assert!($T::MIN == 0, "need unsigned");
412
413        #[ferrocene::prevalidated]
414        fn $fmt_fn(
415            f: &mut fmt::Formatter<'_>,
416            n: $T,
417            is_nonnegative: bool,
418            letter_e: u8
419        ) -> fmt::Result {
420            debug_assert!(letter_e.is_ascii_alphabetic(), "single-byte character");
421
422            // Print the integer as a coefficient in range (-10, 10).
423            let mut exp = n.checked_ilog10().unwrap_or(0) as usize;
424            debug_assert!(n / (10 as $T).pow(exp as u32) < 10);
425
426            // Precisison is counted as the number of digits in the fraction.
427            let mut coef_prec = exp;
428            // Keep the digits as an integer (paired with its coef_prec count).
429            let mut coef = n;
430
431            // A Formatter may set the precision to a fixed number of decimals.
432            let more_prec = match f.precision() {
433                None => {
434                    // Omit any and all trailing zeroes.
435                    while coef_prec != 0 && coef % 10 == 0 {
436                        coef /= 10;
437                        coef_prec -= 1;
438                    }
439                    0
440                },
441
442                Some(fmt_prec) if fmt_prec >= coef_prec => {
443                    // Count the number of additional zeroes needed.
444                    fmt_prec - coef_prec
445                },
446
447                Some(fmt_prec) => {
448                    // Count the number of digits to drop.
449                    let less_prec = coef_prec - fmt_prec;
450                    assert!(less_prec > 0);
451                    // Scale down the coefficient/precision pair. For example,
452                    // coef 123456 gets coef_prec 5 (to make 1.23456). To format
453                    // the number with 2 decimals, i.e., fmt_prec 2, coef should
454                    // be scaled by 10⁵⁻²=1000 to get coef 123 with coef_prec 2.
455
456                    // SAFETY: Any precision less than coef_prec will cause a
457                    // power of ten below the coef value.
458                    let scale = unsafe {
459                        (10 as $T).checked_pow(less_prec as u32).unwrap_unchecked()
460                    };
461                    let floor = coef / scale;
462                    // Round half to even conform documentation.
463                    let over = coef % scale;
464                    let half = scale / 2;
465                    let round_up = if over < half {
466                        0
467                    } else if over > half {
468                        1
469                    } else {
470                        floor & 1 // round odd up to even
471                    };
472                    // Adding one to a scale down of at least 10 won't overflow.
473                    coef = floor + round_up;
474                    coef_prec = fmt_prec;
475
476                    // The round_up may have caused the coefficient to reach 10
477                    // (which is not permitted). For example, anything in range
478                    // [9.95, 10) becomes 10.0 when adjusted to precision 1.
479                    if round_up != 0 && coef.checked_ilog10().unwrap_or(0) as usize > coef_prec {
480                        debug_assert_eq!(coef, (10 as $T).pow(coef_prec as u32 + 1));
481                        coef /= 10; // drop one trailing zero
482                        exp += 1;   // one power of ten higher
483                    }
484                    0
485                },
486            };
487
488            // Allocate a text buffer with lazy initialization.
489            const MAX_DEC_N: usize = $T::MAX.ilog10() as usize + 1;
490            const MAX_COEF_LEN: usize = MAX_DEC_N + ".".len();
491            const MAX_TEXT_LEN: usize = MAX_COEF_LEN + "e99".len();
492            let mut buf = [MaybeUninit::<u8>::uninit(); MAX_TEXT_LEN];
493
494            // Encode the coefficient in buf[..coef_len].
495            let (lead_dec, coef_len) = if coef_prec == 0 && more_prec == 0 {
496                (coef, 1_usize) // single digit; no fraction
497            } else {
498                buf[1].write(b'.');
499                let fraction_range = 2..(2 + coef_prec);
500
501                // Consume the least-significant decimals from a working copy.
502                let mut remain = coef;
503                #[cfg(feature = "optimize_for_size")] {
504                    for i in fraction_range.clone().rev() {
505                        let digit = (remain % 10) as usize;
506                        remain /= 10;
507                        buf[i].write(b'0' + digit as u8);
508                    }
509                }
510                #[cfg(not(feature = "optimize_for_size"))] {
511                    // Write digits per two at a time with a lookup table.
512                    for i in fraction_range.clone().skip(1).rev().step_by(2) {
513                        let pair = (remain % 100) as usize;
514                        remain /= 100;
515                        buf[i - 1].write(DECIMAL_PAIRS[pair * 2 + 0]);
516                        buf[i - 0].write(DECIMAL_PAIRS[pair * 2 + 1]);
517                    }
518                    // An odd number of digits leave one digit remaining.
519                    if coef_prec & 1 != 0 {
520                        let digit = (remain % 10) as usize;
521                        remain /= 10;
522                        buf[fraction_range.start].write(b'0' + digit as u8);
523                    }
524                }
525
526                (remain, fraction_range.end)
527            };
528            debug_assert!(lead_dec < 10);
529            debug_assert!(lead_dec != 0 || coef == 0, "significant digits only");
530            buf[0].write(b'0' + lead_dec as u8);
531
532            // SAFETY: The number of decimals is limited, captured by MAX.
533            unsafe { core::hint::assert_unchecked(coef_len <= MAX_COEF_LEN) }
534            // Encode the scale factor in buf[coef_len..text_len].
535            buf[coef_len].write(letter_e);
536            let text_len: usize = match exp {
537                ..10 => {
538                    buf[coef_len + 1].write(b'0' + exp as u8);
539                    coef_len + 2
540                },
541                10..100 => {
542                    #[cfg(feature = "optimize_for_size")] {
543                        buf[coef_len + 1].write(b'0' + (exp / 10) as u8);
544                        buf[coef_len + 2].write(b'0' + (exp % 10) as u8);
545                    }
546                    #[cfg(not(feature = "optimize_for_size"))] {
547                        buf[coef_len + 1].write(DECIMAL_PAIRS[exp * 2 + 0]);
548                        buf[coef_len + 2].write(DECIMAL_PAIRS[exp * 2 + 1]);
549                    }
550                    coef_len + 3
551                },
552                #[ferrocene::annotation("Branch is unreachable. See SAFETY comment below.")]
553                _ => {
554                    const { assert!($T::MAX.ilog10() < 100) };
555                    // SAFETY: A `u256::MAX` would get exponent 77.
556                    unsafe { core::hint::unreachable_unchecked() }
557                }
558            };
559            // SAFETY: All bytes up until text_len have been set.
560            let text = unsafe { buf[..text_len].assume_init_ref() };
561
562            if more_prec == 0 {
563                // SAFETY: Text is set with ASCII exclusively: either a decimal,
564                // or a LETTER_E, or a dot. ASCII implies valid UTF-8.
565                let as_str = unsafe { str::from_utf8_unchecked(text) };
566                f.pad_integral(is_nonnegative, "", as_str)
567            } else {
568                let parts = &[
569                    numfmt::Part::Copy(&text[..coef_len]),
570                    numfmt::Part::Zero(more_prec),
571                    numfmt::Part::Copy(&text[coef_len..]),
572                ];
573                let sign = if !is_nonnegative {
574                    "-"
575                } else if f.sign_plus() {
576                    "+"
577                } else {
578                    ""
579                };
580                // SAFETY: Text is set with ASCII exclusively: either a decimal,
581                // or a LETTER_E, or a dot. ASCII implies valid UTF-8.
582                unsafe { f.pad_formatted_parts(&numfmt::Formatted { sign, parts }) }
583            }
584        }
585
586        $(
587        const _: () = {
588            assert!($Signed::MIN < 0, "need signed");
589            assert!($Unsigned::MIN == 0, "need unsigned");
590            assert!($Signed::BITS == $Unsigned::BITS, "need counterparts");
591            assert!($Signed::BITS <= $T::BITS, "need lossless conversion");
592            assert!($Unsigned::BITS <= $T::BITS, "need lossless conversion");
593        };
594        #[stable(feature = "integer_exp_format", since = "1.42.0")]
595        impl fmt::LowerExp for $Signed {
596            #[ferrocene::prevalidated]
597            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
598                $fmt_fn(f, self.unsigned_abs() as $T, *self >= 0, b'e')
599            }
600        }
601        #[stable(feature = "integer_exp_format", since = "1.42.0")]
602        impl fmt::LowerExp for $Unsigned {
603            #[ferrocene::prevalidated]
604            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
605                $fmt_fn(f, *self as $T, true, b'e')
606            }
607        }
608        #[stable(feature = "integer_exp_format", since = "1.42.0")]
609        impl fmt::UpperExp for $Signed {
610            #[ferrocene::prevalidated]
611            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
612                $fmt_fn(f, self.unsigned_abs() as $T, *self >= 0, b'E')
613            }
614        }
615        #[stable(feature = "integer_exp_format", since = "1.42.0")]
616        impl fmt::UpperExp for $Unsigned {
617            #[ferrocene::prevalidated]
618            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
619                $fmt_fn(f, *self as $T, true, b'E')
620            }
621        }
622        )*
623
624    };
625}
626
627impl_Debug! {
628    i8 i16 i32 i64 i128 isize
629    u8 u16 u32 u64 u128 usize
630}
631
632// Include wasm32 in here since it doesn't reflect the native pointer size, and
633// often cares strongly about getting a smaller code size.
634#[cfg(any(target_pointer_width = "64", target_arch = "wasm32"))]
635#[doc(auto_cfg = false)]
636mod imp {
637    use super::*;
638    impl_Display!(i8, u8, i16, u16, i32, u32, i64, u64, isize, usize; as u64 into display_u64);
639    impl_Exp!(i8, u8, i16, u16, i32, u32, i64, u64, isize, usize; as u64 into exp_u64);
640}
641
642#[cfg(not(any(target_pointer_width = "64", target_arch = "wasm32")))]
643#[doc(auto_cfg = false)]
644mod imp {
645    use super::*;
646    impl_Display!(i8, u8, i16, u16, i32, u32, isize, usize; as u32 into display_u32);
647    impl_Display!(i64, u64; as u64 into display_u64);
648
649    impl_Exp!(i8, u8, i16, u16, i32, u32, isize, usize; as u32 into exp_u32);
650    impl_Exp!(i64, u64; as u64 into exp_u64);
651}
652impl_Exp!(i128, u128; as u128 into exp_u128);
653
654const U128_MAX_DEC_N: usize = u128::MAX.ilog10() as usize + 1;
655
656#[stable(feature = "rust1", since = "1.0.0")]
657impl fmt::Display for u128 {
658    #[ferrocene::prevalidated]
659    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
660        let mut buf = [MaybeUninit::<u8>::uninit(); U128_MAX_DEC_N];
661
662        // SAFETY: `buf` is always big enough to contain all the digits.
663        unsafe { f.pad_integral(true, "", self._fmt(&mut buf)) }
664    }
665}
666
667#[stable(feature = "rust1", since = "1.0.0")]
668impl fmt::Display for i128 {
669    #[ferrocene::prevalidated]
670    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
671        // This is not a typo, we use the maximum number of digits of `u128`, hence why we use
672        // `U128_MAX_DEC_N`.
673        let mut buf = [MaybeUninit::<u8>::uninit(); U128_MAX_DEC_N];
674
675        let is_nonnegative = *self >= 0;
676        // SAFETY: `buf` is always big enough to contain all the digits.
677        unsafe { f.pad_integral(is_nonnegative, "", self.unsigned_abs()._fmt(&mut buf)) }
678    }
679}
680
681impl u128 {
682    /// Format optimized for u128. Computation of 128 bits is limited by processing
683    /// in batches of 16 decimals at a time.
684    #[doc(hidden)]
685    #[unstable(
686        feature = "fmt_internals",
687        reason = "specialized method meant to only be used by `SpecToString` implementation",
688        issue = "none"
689    )]
690    #[ferrocene::prevalidated]
691    pub unsafe fn _fmt<'a>(self, buf: &'a mut [MaybeUninit<u8>]) -> &'a str {
692        // SAFETY: `buf` will always be big enough to contain all digits.
693        let offset = unsafe { self._fmt_inner(buf) };
694        // SAFETY: Starting from `offset`, all elements of the slice have been set.
695        unsafe { slice_buffer_to_str(buf, offset) }
696    }
697
698    #[ferrocene::prevalidated]
699    unsafe fn _fmt_inner(self, buf: &mut [MaybeUninit<u8>]) -> usize {
700        // Optimize common-case zero, which would also need special treatment due to
701        // its "leading" zero.
702        if self == 0 {
703            let offset = buf.len() - 1;
704            buf[offset].write(b'0');
705            return offset;
706        }
707        // Take the 16 least-significant decimals.
708        let (quot_1e16, mod_1e16) = div_rem_1e16(self);
709        let (mut remain, mut offset) = if quot_1e16 == 0 {
710            (mod_1e16, U128_MAX_DEC_N)
711        } else {
712            // Write digits at buf[23..39].
713            //
714            // SAFETY: `mod_1e16 < 1e16` (remainder), and `U128_MAX_DEC_N - 16 + 16 == buf.len()`.
715            unsafe { enc_16lsd::<{ U128_MAX_DEC_N - 16 }>(buf, mod_1e16) };
716
717            // Take another 16 decimals.
718            let (quot2, mod2) = div_rem_1e16(quot_1e16);
719            if quot2 == 0 {
720                (mod2, U128_MAX_DEC_N - 16)
721            } else {
722                // Write digits at buf[7..23].
723                //
724                // SAFETY: `mod2 < 1e16` (remainder), and `U128_MAX_DEC_N - 32 + 16 <= buf.len()`.
725                unsafe { enc_16lsd::<{ U128_MAX_DEC_N - 32 }>(buf, mod2) };
726
727                // Quot2 has at most 7 decimals remaining after two 1e16 divisions.
728                (quot2 as u64, U128_MAX_DEC_N - 32)
729            }
730        };
731
732        // Format per four digits from the lookup table.
733        while remain > 999 {
734            // SAFETY: All of the decimals fit in buf due to U128_MAX_DEC_N
735            // and the while condition ensures at least 4 more decimals.
736            unsafe { core::hint::assert_unchecked(offset >= 4) }
737            // SAFETY: The offset counts down from its initial buf.len()
738            // without underflow due to the previous precondition.
739            unsafe { core::hint::assert_unchecked(offset <= buf.len()) }
740            offset -= 4;
741
742            let quad = remain % 1_00_00;
743            remain /= 1_00_00;
744
745            // SAFETY: quad is a remainder modulo 10_000. The offset checks
746            // above reserve exactly four bytes in buf.
747            unsafe {
748                write_quad(buf.get_unchecked_mut(offset..offset + 4), quad);
749            }
750        }
751
752        // Format per two digits from the lookup table.
753        if remain > 9 {
754            // SAFETY: All of the decimals fit in buf due to U128_MAX_DEC_N
755            // and the if condition ensures at least 2 more decimals.
756            unsafe { core::hint::assert_unchecked(offset >= 2) }
757            // SAFETY: The offset counts down from its initial buf.len()
758            // without underflow due to the previous precondition.
759            unsafe { core::hint::assert_unchecked(offset <= buf.len()) }
760            offset -= 2;
761
762            let pair = (remain % 100) as usize;
763            remain /= 100;
764            buf[offset + 0].write(DECIMAL_PAIRS[pair * 2 + 0]);
765            buf[offset + 1].write(DECIMAL_PAIRS[pair * 2 + 1]);
766        }
767
768        // Format the last remaining digit, if any.
769        if remain != 0 {
770            // SAFETY: All of the decimals fit in buf due to U128_MAX_DEC_N
771            // and the if condition ensures (at least) 1 more decimals.
772            unsafe { core::hint::assert_unchecked(offset >= 1) }
773            // SAFETY: The offset counts down from its initial buf.len()
774            // without underflow due to the previous precondition.
775            unsafe { core::hint::assert_unchecked(offset <= buf.len()) }
776            offset -= 1;
777
778            // Either the compiler sees that remain < 10, or it prevents
779            // a boundary check up next.
780            let last = (remain & 15) as usize;
781            buf[offset].write(DECIMAL_PAIRS[last * 2 + 1]);
782            // not used: remain = 0;
783        }
784        offset
785    }
786
787    /// Formats this integer as an unsigned decimal number, using the memory pointed to by
788    /// `buf` as storage for the returned string slice.
789    ///
790    /// This method can be used to convert integers to strings without involving the
791    /// dynamic dispatch that using [`Display`][fmt::Display] would.
792    /// This may be more efficient in situations where [`fmt`] is not otherwise used.
793    ///
794    /// # Examples
795    ///
796    /// ```
797    /// use core::fmt::NumBuffer;
798    ///
799    /// let n = 0u128;
800    /// let mut buf = NumBuffer::new();
801    /// assert_eq!(n.format_into(&mut buf), "0");
802    ///
803    /// let n1 = 32u128;
804    /// let mut buf1 = NumBuffer::new();
805    /// assert_eq!(n1.format_into(&mut buf1), "32");
806    ///
807    /// let n2 = u128::MAX;
808    /// let mut buf2 = NumBuffer::new();
809    /// assert_eq!(n2.format_into(&mut buf2), u128::MAX.to_string());
810    /// ```
811    #[ferrocene::prevalidated]
812    #[stable(feature = "int_format_into", since = "1.98.0")]
813    pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
814        let diff = buf.buf.len() - U128_MAX_DEC_N;
815        // FIXME: Once const generics are better, use `NumberBufferTrait::BUF_SIZE` as generic const
816        // for `fmt_u128_inner`.
817        //
818        // In the meantime, we have to use a slice starting at index 1 and add 1 to the returned
819        // offset to ensure the number is correctly generated at the end of the buffer.
820        // SAFETY: `diff` will always be between 0 and its initial value.
821        unsafe { self._fmt(buf.buf.get_unchecked_mut(diff..)) }
822    }
823}
824
825impl i128 {
826    /// Formats this integer as a signed decimal number, using the memory pointed to by
827    /// `buf` as storage for the returned string slice.
828    ///
829    /// This method can be used to convert integers to strings without involving the
830    /// dynamic dispatch that using [`Display`][fmt::Display] would.
831    /// This may be more efficient in situations where [`fmt`] is not otherwise used.
832    ///
833    /// # Examples
834    ///
835    /// ```
836    /// use core::fmt::NumBuffer;
837    ///
838    /// let n = 0i128;
839    /// let mut buf = NumBuffer::new();
840    /// assert_eq!(n.format_into(&mut buf), "0");
841    ///
842    /// let n1 = i128::MIN;
843    /// assert_eq!(n1.format_into(&mut buf), i128::MIN.to_string());
844    ///
845    /// let n2 = i128::MAX;
846    /// assert_eq!(n2.format_into(&mut buf), i128::MAX.to_string());
847    /// ```
848    #[ferrocene::prevalidated]
849    #[stable(feature = "int_format_into", since = "1.98.0")]
850    pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
851        let diff = buf.buf.len() - U128_MAX_DEC_N;
852        // FIXME: Once const generics are better, use `NumberBufferTrait::BUF_SIZE` as generic const
853        // for `fmt_u128_inner`.
854        //
855        // In the meantime, we have to use a slice starting at index 1 and add 1 to the returned
856        // offset to ensure the number is correctly generated at the end of the buffer.
857        let mut offset =
858            // SAFETY: `buf` will always be big enough to contain all digits.
859            unsafe { self.unsigned_abs()._fmt_inner(buf.buf.get_unchecked_mut(diff..)) };
860        // We put back the offset at the right position.
861        offset += diff;
862        // Only difference between signed and unsigned are these 4 lines.
863        if self < 0 {
864            offset -= 1;
865            // SAFETY: `buf` will always be big enough to contain all digits plus the minus sign.
866            unsafe {
867                buf.buf.get_unchecked_mut(offset).write(b'-');
868            }
869        }
870        // SAFETY: Starting from `offset`, all elements of the slice have been set.
871        unsafe { slice_buffer_to_str(&buf.buf, offset) }
872    }
873}
874
875/// Writes `quad` as exactly four digits (for example: `42` becomes `"0042"`).
876///
877/// # Safety
878///
879/// `quad` must be below 10_000 and `buf` must contain exactly four bytes.
880#[ferrocene::prevalidated]
881#[inline(always)]
882unsafe fn write_quad(buf: &mut [MaybeUninit<u8>], quad: u64) {
883    // SAFETY: These are this function's caller-provided invariants.
884    unsafe {
885        core::hint::assert_unchecked(quad < 10_000);
886        core::hint::assert_unchecked(buf.len() == 4);
887    }
888
889    let quad = quad as u32;
890
891    // Note: this is equivalent to `quad / 100`, but contains no division instructions.
892    let high = (quad * const { (1 << 19) / 100 + 1 }) >> 19;
893    let low = quad - high * 100;
894    let high = high as usize;
895    let low = low as usize;
896
897    // SAFETY: `high` and `low` are below 100 because `quad` is below 10_000.
898    unsafe { core::hint::assert_unchecked(high < 100 && low < 100) }
899
900    buf[0..2].write_copy_of_slice(&DECIMAL_PAIRS[high * 2..high * 2 + 2]);
901    buf[2..4].write_copy_of_slice(&DECIMAL_PAIRS[low * 2..low * 2 + 2]);
902}
903
904/// Encodes the 16 least-significant decimals of n into `buf[OFFSET .. OFFSET +
905/// 16 ]`.
906///
907/// # Safety
908///
909/// `n` must be below 1e16, and `buf` must be at least `OFFSET + 16` bytes long.
910#[ferrocene::prevalidated]
911unsafe fn enc_16lsd<const OFFSET: usize>(buf: &mut [MaybeUninit<u8>], n: u64) {
912    // SAFETY: Every caller passes a remainder produced by division by 10^16,
913    // and every used `OFFSET` specialization reserves sixteen bytes in `buf`.
914    unsafe {
915        core::hint::assert_unchecked(n < 10_000_000_000_000_000);
916        core::hint::assert_unchecked(OFFSET + 16 <= buf.len());
917    }
918
919    // Peel four digits at a time from right to left (12345678 -> 1234 | 5678).
920    // Since 10_000 is constant, LLVM replaces each division with multiply or shift.
921    let mut remain = n;
922
923    for quad_index in (1..4).rev() {
924        let quad = remain % 1_00_00;
925        remain /= 1_00_00;
926
927        // SAFETY: `OFFSET + quad_index * 4` starts one of the four
928        // non-overlapping four-byte regions proven in bounds above.
929        unsafe {
930            write_quad(
931                buf.get_unchecked_mut(OFFSET + quad_index * 4..OFFSET + (quad_index + 1) * 4),
932                quad,
933            );
934        }
935    }
936
937    // SAFETY: OFFSET starts the first four-byte region proven in bounds above.
938    unsafe {
939        write_quad(buf.get_unchecked_mut(OFFSET..OFFSET + 4), remain);
940    }
941}
942
943/// Euclidean division plus remainder with constant 1E16 basically consumes 16
944/// decimals from n.
945///
946/// The integer division algorithm is based on the following paper:
947///
948///   T. Granlund and P. Montgomery, “Division by Invariant Integers Using Multiplication”
949///   in Proc. of the SIGPLAN94 Conference on Programming Language Design and
950///   Implementation, 1994, pp. 61–72
951///
952#[inline]
953#[ferrocene::prevalidated]
954fn div_rem_1e16(n: u128) -> (u128, u64) {
955    const D: u128 = 1_0000_0000_0000_0000;
956    // The check inlines well with the caller flow.
957    if n < D {
958        return (0, n as u64);
959    }
960
961    // These constant values are computed with the CHOOSE_MULTIPLIER procedure
962    // from the Granlund & Montgomery paper, using N=128, prec=128 and d=1E16.
963    const M_HIGH: u128 = 76624777043294442917917351357515459181;
964    const SH_POST: u8 = 51;
965
966    let quot = n.carrying_mul(M_HIGH, 0).1 >> SH_POST;
967    let rem = n - quot * D;
968    (quot, rem as u64)
969}