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` 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 offset = ${concat($fmt_fn, _in_buf_small)}(self.unsigned_abs() as $T, &mut buf.buf);
302 }
303 // Only difference between signed and unsigned are these 4 lines.
304 if self < 0 {
305 offset -= 1;
306 buf.buf[offset].write(b'-');
307 }
308 // SAFETY: Starting from `offset`, all elements of the slice have been set.
309 unsafe { slice_buffer_to_str(&buf.buf, offset) }
310 }
311 }
312
313 impl $Unsigned {
314 /// Formats this integer as an unsigned decimal number, using the memory pointed to by
315 /// `buf` as storage for the returned string slice.
316 ///
317 /// This method can be used to convert integers to strings without involving the
318 /// dynamic dispatch that using [`Display`][fmt::Display] would.
319 /// This may be more efficient in situations where [`fmt`] is not otherwise used.
320 ///
321 /// # Examples
322 ///
323 /// ```
324 /// use core::fmt::NumBuffer;
325 ///
326 #[doc = concat!("let n = 0", stringify!($Unsigned), ";")]
327 /// let mut buf = NumBuffer::new();
328 /// assert_eq!(n.format_into(&mut buf), "0");
329 ///
330 #[doc = concat!("let n1 = 32", stringify!($Unsigned), ";")]
331 /// assert_eq!(n1.format_into(&mut buf), "32");
332 ///
333 #[doc = concat!("let n2 = ", stringify!($Unsigned::MAX), ";")]
334 #[doc = concat!("assert_eq!(n2.format_into(&mut buf), ", stringify!($Unsigned::MAX), ".to_string());")]
335 /// ```
336 #[ferrocene::prevalidated]
337 #[stable(feature = "int_format_into", since = "1.98.0")]
338 pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
339 let offset;
340
341 #[cfg(not(feature = "optimize_for_size"))]
342 // SAFETY: `buf` will always be big enough to contain all digits.
343 unsafe {
344 offset = self._fmt_inner(&mut buf.buf);
345 }
346 #[cfg(feature = "optimize_for_size")]
347 {
348 // Lossless conversion (with as) is asserted at the top of
349 // this macro.
350 offset = ${concat($fmt_fn, _in_buf_small)}(self as $T, &mut buf.buf);
351 }
352 // SAFETY: Starting from `offset`, all elements of the slice have been set.
353 unsafe { slice_buffer_to_str(&buf.buf, offset) }
354 }
355 }
356
357 )*
358
359 #[cfg(feature = "optimize_for_size")]
360 fn ${concat($fmt_fn, _in_buf_small)}(mut n: $T, buf: &mut [MaybeUninit::<u8>]) -> usize {
361 let mut curr = buf.len();
362
363 // SAFETY: To show that it's OK to copy into `buf_ptr`, notice that at the beginning
364 // `curr == buf.len() == 39 > log(n)` since `n < 2^128 < 10^39`, and at
365 // each step this is kept the same as `n` is divided. Since `n` is always
366 // non-negative, this means that `curr > 0` so `buf_ptr[curr..curr + 1]`
367 // is safe to access.
368 loop {
369 curr -= 1;
370 buf[curr].write((n % 10) as u8 + b'0');
371 n /= 10;
372
373 if n == 0 {
374 break;
375 }
376 }
377 curr
378 }
379
380 #[cfg(feature = "optimize_for_size")]
381 fn ${concat($fmt_fn, _small)}(n: $T, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382 const MAX_DEC_N: usize = $T::MAX.ilog10() as usize + 1;
383 let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];
384
385 let offset = ${concat($fmt_fn, _in_buf_small)}(n, &mut buf);
386 // SAFETY: Starting from `offset`, all elements of the slice have been set.
387 let buf_slice = unsafe { slice_buffer_to_str(&buf, offset) };
388 f.pad_integral(is_nonnegative, "", buf_slice)
389 }
390 };
391}
392
393macro_rules! impl_Exp {
394 ($($Signed:ident, $Unsigned:ident),* ; as $T:ident into $fmt_fn:ident) => {
395 const _: () = assert!($T::MIN == 0, "need unsigned");
396
397 #[ferrocene::prevalidated]
398 fn $fmt_fn(
399 f: &mut fmt::Formatter<'_>,
400 n: $T,
401 is_nonnegative: bool,
402 letter_e: u8
403 ) -> fmt::Result {
404 debug_assert!(letter_e.is_ascii_alphabetic(), "single-byte character");
405
406 // Print the integer as a coefficient in range (-10, 10).
407 let mut exp = n.checked_ilog10().unwrap_or(0) as usize;
408 debug_assert!(n / (10 as $T).pow(exp as u32) < 10);
409
410 // Precisison is counted as the number of digits in the fraction.
411 let mut coef_prec = exp;
412 // Keep the digits as an integer (paired with its coef_prec count).
413 let mut coef = n;
414
415 // A Formatter may set the precision to a fixed number of decimals.
416 let more_prec = match f.precision() {
417 None => {
418 // Omit any and all trailing zeroes.
419 while coef_prec != 0 && coef % 10 == 0 {
420 coef /= 10;
421 coef_prec -= 1;
422 }
423 0
424 },
425
426 Some(fmt_prec) if fmt_prec >= coef_prec => {
427 // Count the number of additional zeroes needed.
428 fmt_prec - coef_prec
429 },
430
431 Some(fmt_prec) => {
432 // Count the number of digits to drop.
433 let less_prec = coef_prec - fmt_prec;
434 assert!(less_prec > 0);
435 // Scale down the coefficient/precision pair. For example,
436 // coef 123456 gets coef_prec 5 (to make 1.23456). To format
437 // the number with 2 decimals, i.e., fmt_prec 2, coef should
438 // be scaled by 10⁵⁻²=1000 to get coef 123 with coef_prec 2.
439
440 // SAFETY: Any precision less than coef_prec will cause a
441 // power of ten below the coef value.
442 let scale = unsafe {
443 (10 as $T).checked_pow(less_prec as u32).unwrap_unchecked()
444 };
445 let floor = coef / scale;
446 // Round half to even conform documentation.
447 let over = coef % scale;
448 let half = scale / 2;
449 let round_up = if over < half {
450 0
451 } else if over > half {
452 1
453 } else {
454 floor & 1 // round odd up to even
455 };
456 // Adding one to a scale down of at least 10 won't overflow.
457 coef = floor + round_up;
458 coef_prec = fmt_prec;
459
460 // The round_up may have caused the coefficient to reach 10
461 // (which is not permitted). For example, anything in range
462 // [9.95, 10) becomes 10.0 when adjusted to precision 1.
463 if round_up != 0 && coef.checked_ilog10().unwrap_or(0) as usize > coef_prec {
464 debug_assert_eq!(coef, (10 as $T).pow(coef_prec as u32 + 1));
465 coef /= 10; // drop one trailing zero
466 exp += 1; // one power of ten higher
467 }
468 0
469 },
470 };
471
472 // Allocate a text buffer with lazy initialization.
473 const MAX_DEC_N: usize = $T::MAX.ilog10() as usize + 1;
474 const MAX_COEF_LEN: usize = MAX_DEC_N + ".".len();
475 const MAX_TEXT_LEN: usize = MAX_COEF_LEN + "e99".len();
476 let mut buf = [MaybeUninit::<u8>::uninit(); MAX_TEXT_LEN];
477
478 // Encode the coefficient in buf[..coef_len].
479 let (lead_dec, coef_len) = if coef_prec == 0 && more_prec == 0 {
480 (coef, 1_usize) // single digit; no fraction
481 } else {
482 buf[1].write(b'.');
483 let fraction_range = 2..(2 + coef_prec);
484
485 // Consume the least-significant decimals from a working copy.
486 let mut remain = coef;
487 #[cfg(feature = "optimize_for_size")] {
488 for i in fraction_range.clone().rev() {
489 let digit = (remain % 10) as usize;
490 remain /= 10;
491 buf[i].write(b'0' + digit as u8);
492 }
493 }
494 #[cfg(not(feature = "optimize_for_size"))] {
495 // Write digits per two at a time with a lookup table.
496 for i in fraction_range.clone().skip(1).rev().step_by(2) {
497 let pair = (remain % 100) as usize;
498 remain /= 100;
499 buf[i - 1].write(DECIMAL_PAIRS[pair * 2 + 0]);
500 buf[i - 0].write(DECIMAL_PAIRS[pair * 2 + 1]);
501 }
502 // An odd number of digits leave one digit remaining.
503 if coef_prec & 1 != 0 {
504 let digit = (remain % 10) as usize;
505 remain /= 10;
506 buf[fraction_range.start].write(b'0' + digit as u8);
507 }
508 }
509
510 (remain, fraction_range.end)
511 };
512 debug_assert!(lead_dec < 10);
513 debug_assert!(lead_dec != 0 || coef == 0, "significant digits only");
514 buf[0].write(b'0' + lead_dec as u8);
515
516 // SAFETY: The number of decimals is limited, captured by MAX.
517 unsafe { core::hint::assert_unchecked(coef_len <= MAX_COEF_LEN) }
518 // Encode the scale factor in buf[coef_len..text_len].
519 buf[coef_len].write(letter_e);
520 let text_len: usize = match exp {
521 ..10 => {
522 buf[coef_len + 1].write(b'0' + exp as u8);
523 coef_len + 2
524 },
525 10..100 => {
526 #[cfg(feature = "optimize_for_size")] {
527 buf[coef_len + 1].write(b'0' + (exp / 10) as u8);
528 buf[coef_len + 2].write(b'0' + (exp % 10) as u8);
529 }
530 #[cfg(not(feature = "optimize_for_size"))] {
531 buf[coef_len + 1].write(DECIMAL_PAIRS[exp * 2 + 0]);
532 buf[coef_len + 2].write(DECIMAL_PAIRS[exp * 2 + 1]);
533 }
534 coef_len + 3
535 },
536 #[ferrocene::annotation("Branch is unreachable. See SAFETY comment below.")]
537 _ => {
538 const { assert!($T::MAX.ilog10() < 100) };
539 // SAFETY: A `u256::MAX` would get exponent 77.
540 unsafe { core::hint::unreachable_unchecked() }
541 }
542 };
543 // SAFETY: All bytes up until text_len have been set.
544 let text = unsafe { buf[..text_len].assume_init_ref() };
545
546 if more_prec == 0 {
547 // SAFETY: Text is set with ASCII exclusively: either a decimal,
548 // or a LETTER_E, or a dot. ASCII implies valid UTF-8.
549 let as_str = unsafe { str::from_utf8_unchecked(text) };
550 f.pad_integral(is_nonnegative, "", as_str)
551 } else {
552 let parts = &[
553 numfmt::Part::Copy(&text[..coef_len]),
554 numfmt::Part::Zero(more_prec),
555 numfmt::Part::Copy(&text[coef_len..]),
556 ];
557 let sign = if !is_nonnegative {
558 "-"
559 } else if f.sign_plus() {
560 "+"
561 } else {
562 ""
563 };
564 // SAFETY: Text is set with ASCII exclusively: either a decimal,
565 // or a LETTER_E, or a dot. ASCII implies valid UTF-8.
566 unsafe { f.pad_formatted_parts(&numfmt::Formatted { sign, parts }) }
567 }
568 }
569
570 $(
571 const _: () = {
572 assert!($Signed::MIN < 0, "need signed");
573 assert!($Unsigned::MIN == 0, "need unsigned");
574 assert!($Signed::BITS == $Unsigned::BITS, "need counterparts");
575 assert!($Signed::BITS <= $T::BITS, "need lossless conversion");
576 assert!($Unsigned::BITS <= $T::BITS, "need lossless conversion");
577 };
578 #[stable(feature = "integer_exp_format", since = "1.42.0")]
579 impl fmt::LowerExp for $Signed {
580 #[ferrocene::prevalidated]
581 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
582 $fmt_fn(f, self.unsigned_abs() as $T, *self >= 0, b'e')
583 }
584 }
585 #[stable(feature = "integer_exp_format", since = "1.42.0")]
586 impl fmt::LowerExp for $Unsigned {
587 #[ferrocene::prevalidated]
588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589 $fmt_fn(f, *self as $T, true, b'e')
590 }
591 }
592 #[stable(feature = "integer_exp_format", since = "1.42.0")]
593 impl fmt::UpperExp for $Signed {
594 #[ferrocene::prevalidated]
595 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
596 $fmt_fn(f, self.unsigned_abs() as $T, *self >= 0, b'E')
597 }
598 }
599 #[stable(feature = "integer_exp_format", since = "1.42.0")]
600 impl fmt::UpperExp for $Unsigned {
601 #[ferrocene::prevalidated]
602 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
603 $fmt_fn(f, *self as $T, true, b'E')
604 }
605 }
606 )*
607
608 };
609}
610
611impl_Debug! {
612 i8 i16 i32 i64 i128 isize
613 u8 u16 u32 u64 u128 usize
614}
615
616// Include wasm32 in here since it doesn't reflect the native pointer size, and
617// often cares strongly about getting a smaller code size.
618#[cfg(any(target_pointer_width = "64", target_arch = "wasm32"))]
619#[doc(auto_cfg = false)]
620mod imp {
621 use super::*;
622 impl_Display!(i8, u8, i16, u16, i32, u32, i64, u64, isize, usize; as u64 into display_u64);
623 impl_Exp!(i8, u8, i16, u16, i32, u32, i64, u64, isize, usize; as u64 into exp_u64);
624}
625
626#[cfg(not(any(target_pointer_width = "64", target_arch = "wasm32")))]
627#[doc(auto_cfg = false)]
628mod imp {
629 use super::*;
630 impl_Display!(i8, u8, i16, u16, i32, u32, isize, usize; as u32 into display_u32);
631 impl_Display!(i64, u64; as u64 into display_u64);
632
633 impl_Exp!(i8, u8, i16, u16, i32, u32, isize, usize; as u32 into exp_u32);
634 impl_Exp!(i64, u64; as u64 into exp_u64);
635}
636impl_Exp!(i128, u128; as u128 into exp_u128);
637
638const U128_MAX_DEC_N: usize = u128::MAX.ilog10() as usize + 1;
639
640#[stable(feature = "rust1", since = "1.0.0")]
641impl fmt::Display for u128 {
642 #[ferrocene::prevalidated]
643 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
644 let mut buf = [MaybeUninit::<u8>::uninit(); U128_MAX_DEC_N];
645
646 // SAFETY: `buf` is always big enough to contain all the digits.
647 unsafe { f.pad_integral(true, "", self._fmt(&mut buf)) }
648 }
649}
650
651#[stable(feature = "rust1", since = "1.0.0")]
652impl fmt::Display for i128 {
653 #[ferrocene::prevalidated]
654 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 // This is not a typo, we use the maximum number of digits of `u128`, hence why we use
656 // `U128_MAX_DEC_N`.
657 let mut buf = [MaybeUninit::<u8>::uninit(); U128_MAX_DEC_N];
658
659 let is_nonnegative = *self >= 0;
660 // SAFETY: `buf` is always big enough to contain all the digits.
661 unsafe { f.pad_integral(is_nonnegative, "", self.unsigned_abs()._fmt(&mut buf)) }
662 }
663}
664
665impl u128 {
666 /// Format optimized for u128. Computation of 128 bits is limited by processing
667 /// in batches of 16 decimals at a time.
668 #[doc(hidden)]
669 #[unstable(
670 feature = "fmt_internals",
671 reason = "specialized method meant to only be used by `SpecToString` implementation",
672 issue = "none"
673 )]
674 #[ferrocene::prevalidated]
675 pub unsafe fn _fmt<'a>(self, buf: &'a mut [MaybeUninit<u8>]) -> &'a str {
676 // SAFETY: `buf` will always be big enough to contain all digits.
677 let offset = unsafe { self._fmt_inner(buf) };
678 // SAFETY: Starting from `offset`, all elements of the slice have been set.
679 unsafe { slice_buffer_to_str(buf, offset) }
680 }
681
682 #[ferrocene::prevalidated]
683 unsafe fn _fmt_inner(self, buf: &mut [MaybeUninit<u8>]) -> usize {
684 // Optimize common-case zero, which would also need special treatment due to
685 // its "leading" zero.
686 if self == 0 {
687 let offset = buf.len() - 1;
688 buf[offset].write(b'0');
689 return offset;
690 }
691 // Take the 16 least-significant decimals.
692 let (quot_1e16, mod_1e16) = div_rem_1e16(self);
693 let (mut remain, mut offset) = if quot_1e16 == 0 {
694 (mod_1e16, U128_MAX_DEC_N)
695 } else {
696 // Write digits at buf[23..39].
697 //
698 // SAFETY: `mod_1e16 < 1e16` (remainder), and `U128_MAX_DEC_N - 16 + 16 == buf.len()`.
699 unsafe { enc_16lsd::<{ U128_MAX_DEC_N - 16 }>(buf, mod_1e16) };
700
701 // Take another 16 decimals.
702 let (quot2, mod2) = div_rem_1e16(quot_1e16);
703 if quot2 == 0 {
704 (mod2, U128_MAX_DEC_N - 16)
705 } else {
706 // Write digits at buf[7..23].
707 //
708 // SAFETY: `mod2 < 1e16` (remainder), and `U128_MAX_DEC_N - 32 + 16 <= buf.len()`.
709 unsafe { enc_16lsd::<{ U128_MAX_DEC_N - 32 }>(buf, mod2) };
710
711 // Quot2 has at most 7 decimals remaining after two 1e16 divisions.
712 (quot2 as u64, U128_MAX_DEC_N - 32)
713 }
714 };
715
716 // Format per four digits from the lookup table.
717 while remain > 999 {
718 // SAFETY: All of the decimals fit in buf due to U128_MAX_DEC_N
719 // and the while condition ensures at least 4 more decimals.
720 unsafe { core::hint::assert_unchecked(offset >= 4) }
721 // SAFETY: The offset counts down from its initial buf.len()
722 // without underflow due to the previous precondition.
723 unsafe { core::hint::assert_unchecked(offset <= buf.len()) }
724 offset -= 4;
725
726 let quad = remain % 1_00_00;
727 remain /= 1_00_00;
728
729 // SAFETY: quad is a remainder modulo 10_000. The offset checks
730 // above reserve exactly four bytes in buf.
731 unsafe {
732 write_quad(buf.get_unchecked_mut(offset..offset + 4), quad);
733 }
734 }
735
736 // Format per two digits from the lookup table.
737 if remain > 9 {
738 // SAFETY: All of the decimals fit in buf due to U128_MAX_DEC_N
739 // and the if condition ensures at least 2 more decimals.
740 unsafe { core::hint::assert_unchecked(offset >= 2) }
741 // SAFETY: The offset counts down from its initial buf.len()
742 // without underflow due to the previous precondition.
743 unsafe { core::hint::assert_unchecked(offset <= buf.len()) }
744 offset -= 2;
745
746 let pair = (remain % 100) as usize;
747 remain /= 100;
748 buf[offset + 0].write(DECIMAL_PAIRS[pair * 2 + 0]);
749 buf[offset + 1].write(DECIMAL_PAIRS[pair * 2 + 1]);
750 }
751
752 // Format the last remaining digit, if any.
753 if remain != 0 {
754 // SAFETY: All of the decimals fit in buf due to U128_MAX_DEC_N
755 // and the if condition ensures (at least) 1 more decimals.
756 unsafe { core::hint::assert_unchecked(offset >= 1) }
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 -= 1;
761
762 // Either the compiler sees that remain < 10, or it prevents
763 // a boundary check up next.
764 let last = (remain & 15) as usize;
765 buf[offset].write(DECIMAL_PAIRS[last * 2 + 1]);
766 // not used: remain = 0;
767 }
768 offset
769 }
770
771 /// Formats this integer as an unsigned decimal number, using the memory pointed to by
772 /// `buf` as storage for the returned string slice.
773 ///
774 /// This method can be used to convert integers to strings without involving the
775 /// dynamic dispatch that using [`Display`][fmt::Display] would.
776 /// This may be more efficient in situations where [`fmt`] is not otherwise used.
777 ///
778 /// # Examples
779 ///
780 /// ```
781 /// use core::fmt::NumBuffer;
782 ///
783 /// let n = 0u128;
784 /// let mut buf = NumBuffer::new();
785 /// assert_eq!(n.format_into(&mut buf), "0");
786 ///
787 /// let n1 = 32u128;
788 /// let mut buf1 = NumBuffer::new();
789 /// assert_eq!(n1.format_into(&mut buf1), "32");
790 ///
791 /// let n2 = u128::MAX;
792 /// let mut buf2 = NumBuffer::new();
793 /// assert_eq!(n2.format_into(&mut buf2), u128::MAX.to_string());
794 /// ```
795 #[ferrocene::prevalidated]
796 #[stable(feature = "int_format_into", since = "1.98.0")]
797 pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
798 let diff = buf.buf.len() - U128_MAX_DEC_N;
799 // FIXME: Once const generics are better, use `NumberBufferTrait::BUF_SIZE` as generic const
800 // for `fmt_u128_inner`.
801 //
802 // In the meantime, we have to use a slice starting at index 1 and add 1 to the returned
803 // offset to ensure the number is correctly generated at the end of the buffer.
804 // SAFETY: `diff` will always be between 0 and its initial value.
805 unsafe { self._fmt(buf.buf.get_unchecked_mut(diff..)) }
806 }
807}
808
809impl i128 {
810 /// Formats this integer as a signed decimal number, using the memory pointed to by
811 /// `buf` as storage for the returned string slice.
812 ///
813 /// This method can be used to convert integers to strings without involving the
814 /// dynamic dispatch that using [`Display`][fmt::Display] would.
815 /// This may be more efficient in situations where [`fmt`] is not otherwise used.
816 ///
817 /// # Examples
818 ///
819 /// ```
820 /// use core::fmt::NumBuffer;
821 ///
822 /// let n = 0i128;
823 /// let mut buf = NumBuffer::new();
824 /// assert_eq!(n.format_into(&mut buf), "0");
825 ///
826 /// let n1 = i128::MIN;
827 /// assert_eq!(n1.format_into(&mut buf), i128::MIN.to_string());
828 ///
829 /// let n2 = i128::MAX;
830 /// assert_eq!(n2.format_into(&mut buf), i128::MAX.to_string());
831 /// ```
832 #[ferrocene::prevalidated]
833 #[stable(feature = "int_format_into", since = "1.98.0")]
834 pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
835 let diff = buf.buf.len() - U128_MAX_DEC_N;
836 // FIXME: Once const generics are better, use `NumberBufferTrait::BUF_SIZE` as generic const
837 // for `fmt_u128_inner`.
838 //
839 // In the meantime, we have to use a slice starting at index 1 and add 1 to the returned
840 // offset to ensure the number is correctly generated at the end of the buffer.
841 let mut offset =
842 // SAFETY: `buf` will always be big enough to contain all digits.
843 unsafe { self.unsigned_abs()._fmt_inner(buf.buf.get_unchecked_mut(diff..)) };
844 // We put back the offset at the right position.
845 offset += diff;
846 // Only difference between signed and unsigned are these 4 lines.
847 if self < 0 {
848 offset -= 1;
849 // SAFETY: `buf` will always be big enough to contain all digits plus the minus sign.
850 unsafe {
851 buf.buf.get_unchecked_mut(offset).write(b'-');
852 }
853 }
854 // SAFETY: Starting from `offset`, all elements of the slice have been set.
855 unsafe { slice_buffer_to_str(&buf.buf, offset) }
856 }
857}
858
859/// Writes `quad` as exactly four digits (for example: `42` becomes `"0042"`).
860///
861/// # Safety
862///
863/// `quad` must be below 10_000 and `buf` must contain exactly four bytes.
864#[ferrocene::prevalidated]
865#[inline(always)]
866unsafe fn write_quad(buf: &mut [MaybeUninit<u8>], quad: u64) {
867 // SAFETY: These are this function's caller-provided invariants.
868 unsafe {
869 core::hint::assert_unchecked(quad < 10_000);
870 core::hint::assert_unchecked(buf.len() == 4);
871 }
872
873 let quad = quad as u32;
874
875 // Note: this is equivalent to `quad / 100`, but contains no division instructions.
876 let high = (quad * const { (1 << 19) / 100 + 1 }) >> 19;
877 let low = quad - high * 100;
878 let high = high as usize;
879 let low = low as usize;
880
881 // SAFETY: `high` and `low` are below 100 because `quad` is below 10_000.
882 unsafe { core::hint::assert_unchecked(high < 100 && low < 100) }
883
884 buf[0..2].write_copy_of_slice(&DECIMAL_PAIRS[high * 2..high * 2 + 2]);
885 buf[2..4].write_copy_of_slice(&DECIMAL_PAIRS[low * 2..low * 2 + 2]);
886}
887
888/// Encodes the 16 least-significant decimals of n into `buf[OFFSET .. OFFSET +
889/// 16 ]`.
890///
891/// # Safety
892///
893/// `n` must be below 1e16, and `buf` must be at least `OFFSET + 16` bytes long.
894#[ferrocene::prevalidated]
895unsafe fn enc_16lsd<const OFFSET: usize>(buf: &mut [MaybeUninit<u8>], n: u64) {
896 // SAFETY: Every caller passes a remainder produced by division by 10^16,
897 // and every used `OFFSET` specialization reserves sixteen bytes in `buf`.
898 unsafe {
899 core::hint::assert_unchecked(n < 10_000_000_000_000_000);
900 core::hint::assert_unchecked(OFFSET + 16 <= buf.len());
901 }
902
903 // Peel four digits at a time from right to left (12345678 -> 1234 | 5678).
904 // Since 10_000 is constant, LLVM replaces each division with multiply or shift.
905 let mut remain = n;
906
907 for quad_index in (1..4).rev() {
908 let quad = remain % 1_00_00;
909 remain /= 1_00_00;
910
911 // SAFETY: `OFFSET + quad_index * 4` starts one of the four
912 // non-overlapping four-byte regions proven in bounds above.
913 unsafe {
914 write_quad(
915 buf.get_unchecked_mut(OFFSET + quad_index * 4..OFFSET + (quad_index + 1) * 4),
916 quad,
917 );
918 }
919 }
920
921 // SAFETY: OFFSET starts the first four-byte region proven in bounds above.
922 unsafe {
923 write_quad(buf.get_unchecked_mut(OFFSET..OFFSET + 4), remain);
924 }
925}
926
927/// Euclidean division plus remainder with constant 1E16 basically consumes 16
928/// decimals from n.
929///
930/// The integer division algorithm is based on the following paper:
931///
932/// T. Granlund and P. Montgomery, “Division by Invariant Integers Using Multiplication”
933/// in Proc. of the SIGPLAN94 Conference on Programming Language Design and
934/// Implementation, 1994, pp. 61–72
935///
936#[inline]
937#[ferrocene::prevalidated]
938fn div_rem_1e16(n: u128) -> (u128, u64) {
939 const D: u128 = 1_0000_0000_0000_0000;
940 // The check inlines well with the caller flow.
941 if n < D {
942 return (0, n as u64);
943 }
944
945 // These constant values are computed with the CHOOSE_MULTIPLIER procedure
946 // from the Granlund & Montgomery paper, using N=128, prec=128 and d=1E16.
947 const M_HIGH: u128 = 76624777043294442917917351357515459181;
948 const SH_POST: u8 = 51;
949
950 let quot = n.carrying_mul(M_HIGH, 0).1 >> SH_POST;
951 let rem = n - quot * D;
952 (quot, rem as u64)
953}