Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d7da6f7

Browse files
fmt::DisplayInt abstraction obsolete with better macro
1 parent 4ad8606 commit d7da6f7

File tree

1 file changed

+63
-94
lines changed

1 file changed

+63
-94
lines changed

‎library/core/src/fmt/num.rs‎

Lines changed: 63 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,8 @@
33
use crate::fmt::NumBuffer;
44
use crate::mem::MaybeUninit;
55
use crate::num::fmt as numfmt;
6-
use crate::ops::{Div, Rem, Sub};
76
use crate::{fmt, ptr, slice, str};
87

9-
#[doc(hidden)]
10-
trait DisplayInt:
11-
PartialEq + PartialOrd + Div<Output = Self> + Rem<Output = Self> + Sub<Output = Self> + Copy
12-
{
13-
#[cfg(not(any(target_pointer_width = "64", target_arch = "wasm32")))]
14-
fn to_u32(&self) -> u32;
15-
fn to_u64(&self) -> u64;
16-
fn to_u128(&self) -> u128;
17-
}
18-
19-
macro_rules! impl_int {
20-
($($t:ident)*) => (
21-
$(impl DisplayInt for $t {
22-
#[cfg(not(any(target_pointer_width = "64", target_arch = "wasm32")))]
23-
fn to_u32(&self) -> u32 { *self as u32 }
24-
fn to_u64(&self) -> u64 { *self as u64 }
25-
fn to_u128(&self) -> u128 { *self as u128 }
26-
})*
27-
)
28-
}
29-
30-
impl_int! {
31-
i8 i16 i32 i64 i128 isize
32-
u8 u16 u32 u64 u128 usize
33-
}
34-
358
/// Formatting of integers with a non-decimal radix.
369
macro_rules! radix_integer {
3710
(fmt::$Trait:ident for $Signed:ident and $Unsigned:ident, $prefix:literal, $dig_tab:literal) => {
@@ -146,49 +119,51 @@ unsafe fn slice_buffer_to_str(buf: &[MaybeUninit<u8>], offset: usize) -> &str {
146119
}
147120

148121
macro_rules! impl_Display {
149-
($($signed:ident, $unsigned:ident,)* ; as $u:ident via $conv_fn:ident named $gen_name:ident) => {
122+
($($Signed:ident, $Unsigned:ident),* ; as $T:ident into $fmt_fn:ident) => {
150123

151124
$(
152125
#[stable(feature = "rust1", since = "1.0.0")]
153-
impl fmt::Display for $unsigned {
126+
impl fmt::Display for $Unsigned {
154127
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155128
#[cfg(not(feature = "optimize_for_size"))]
156129
{
157-
const MAX_DEC_N: usize = $unsigned::MAX.ilog10() as usize + 1;
158-
// Buffer decimals for $unsigned with right alignment.
130+
const MAX_DEC_N: usize = $Unsigned::MAX.ilog10() as usize + 1;
131+
// Buffer decimals for self with right alignment.
159132
let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];
160133

161134
// SAFETY: `buf` is always big enough to contain all the digits.
162135
unsafe { f.pad_integral(true, "", self._fmt(&mut buf)) }
163136
}
164137
#[cfg(feature = "optimize_for_size")]
165138
{
166-
$gen_name(self.$conv_fn(), true, f)
139+
assert!(Self::BITS <= $T::BITS, "need lossless conversion");
140+
$fmt_fn(self as $T, true, f)
167141
}
168142
}
169143
}
170144

171145
#[stable(feature = "rust1", since = "1.0.0")]
172-
impl fmt::Display for $signed {
146+
impl fmt::Display for $Signed {
173147
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174148
#[cfg(not(feature = "optimize_for_size"))]
175149
{
176-
const MAX_DEC_N: usize = $unsigned::MAX.ilog10() as usize + 1;
177-
// Buffer decimals for $unsigned with right alignment.
150+
const MAX_DEC_N: usize = $Unsigned::MAX.ilog10() as usize + 1;
151+
// Buffer decimals for self with right alignment.
178152
let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];
179153

180154
// SAFETY: `buf` is always big enough to contain all the digits.
181155
unsafe { f.pad_integral(*self >= 0, "", self.unsigned_abs()._fmt(&mut buf)) }
182156
}
183157
#[cfg(feature = "optimize_for_size")]
184158
{
185-
return $gen_name(self.unsigned_abs().$conv_fn(), *self >= 0, f);
159+
assert!(Self::BITS <= $T::BITS, "need lossless conversion");
160+
return $fmt_fn(self.unsigned_abs() as $T, *self >= 0, f);
186161
}
187162
}
188163
}
189164

190165
#[cfg(not(feature = "optimize_for_size"))]
191-
impl $unsigned {
166+
impl $Unsigned {
192167
#[doc(hidden)]
193168
#[unstable(
194169
feature = "fmt_internals",
@@ -209,7 +184,7 @@ macro_rules! impl_Display {
209184
let mut remain = self;
210185

211186
// Format per four digits from the lookup table.
212-
// Four digits need a 16-bit $unsigned or wider.
187+
// Four digits need a 16-bit $Unsigned or wider.
213188
while size_of::<Self>() > 1 && remain > 999.try_into().expect("branch is not hit for types that cannot fit 999 (u8)") {
214189
// SAFETY: All of the decimals fit in buf due to MAX_DEC_N
215190
// and the while condition ensures at least 4 more decimals.
@@ -268,7 +243,7 @@ macro_rules! impl_Display {
268243
}
269244
}
270245

271-
impl $signed {
246+
impl $Signed {
272247
/// Allows users to write an integer (in signed decimal format) into a variable `buf` of
273248
/// type [`NumBuffer`] that is passed by the caller by mutable reference.
274249
///
@@ -278,15 +253,15 @@ macro_rules! impl_Display {
278253
/// #![feature(int_format_into)]
279254
/// use core::fmt::NumBuffer;
280255
///
281-
#[doc = concat!("let n = 0", stringify!($signed), ";")]
256+
#[doc = concat!("let n = 0", stringify!($Signed), ";")]
282257
/// let mut buf = NumBuffer::new();
283258
/// assert_eq!(n.format_into(&mut buf), "0");
284259
///
285-
#[doc = concat!("let n1 = 32", stringify!($signed), ";")]
260+
#[doc = concat!("let n1 = 32", stringify!($Signed), ";")]
286261
/// assert_eq!(n1.format_into(&mut buf), "32");
287262
///
288-
#[doc = concat!("let n2 = ", stringify!($signed::MAX), ";")]
289-
#[doc = concat!("assert_eq!(n2.format_into(&mut buf), ", stringify!($signed::MAX), ".to_string());")]
263+
#[doc = concat!("let n2 = ", stringify!($Signed::MAX), ";")]
264+
#[doc = concat!("assert_eq!(n2.format_into(&mut buf), ", stringify!($Signed::MAX), ".to_string());")]
290265
/// ```
291266
#[unstable(feature = "int_format_into", issue = "138215")]
292267
pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
@@ -299,7 +274,8 @@ macro_rules! impl_Display {
299274
}
300275
#[cfg(feature = "optimize_for_size")]
301276
{
302-
offset = ${concat(_inner_slow_integer_to_str, $gen_name)}(self.unsigned_abs().$conv_fn(), &mut buf.buf);
277+
assert!(Self::BITS <= $T::BITS, "need lossless conversion");
278+
offset = ${concat(_inner_slow_integer_to_str, $fmt_fn)}(self.unsigned_abs() as $T, &mut buf.buf);
303279
}
304280
// Only difference between signed and unsigned are these 4 lines.
305281
if self < 0 {
@@ -311,7 +287,7 @@ macro_rules! impl_Display {
311287
}
312288
}
313289

314-
impl $unsigned {
290+
impl $Unsigned {
315291
/// Allows users to write an integer (in signed decimal format) into a variable `buf` of
316292
/// type [`NumBuffer`] that is passed by the caller by mutable reference.
317293
///
@@ -321,15 +297,15 @@ macro_rules! impl_Display {
321297
/// #![feature(int_format_into)]
322298
/// use core::fmt::NumBuffer;
323299
///
324-
#[doc = concat!("let n = 0", stringify!($unsigned), ";")]
300+
#[doc = concat!("let n = 0", stringify!($Unsigned), ";")]
325301
/// let mut buf = NumBuffer::new();
326302
/// assert_eq!(n.format_into(&mut buf), "0");
327303
///
328-
#[doc = concat!("let n1 = 32", stringify!($unsigned), ";")]
304+
#[doc = concat!("let n1 = 32", stringify!($Unsigned), ";")]
329305
/// assert_eq!(n1.format_into(&mut buf), "32");
330306
///
331-
#[doc = concat!("let n2 = ", stringify!($unsigned::MAX), ";")]
332-
#[doc = concat!("assert_eq!(n2.format_into(&mut buf), ", stringify!($unsigned::MAX), ".to_string());")]
307+
#[doc = concat!("let n2 = ", stringify!($Unsigned::MAX), ";")]
308+
#[doc = concat!("assert_eq!(n2.format_into(&mut buf), ", stringify!($Unsigned::MAX), ".to_string());")]
333309
/// ```
334310
#[unstable(feature = "int_format_into", issue = "138215")]
335311
pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
@@ -342,7 +318,8 @@ macro_rules! impl_Display {
342318
}
343319
#[cfg(feature = "optimize_for_size")]
344320
{
345-
offset = ${concat(_inner_slow_integer_to_str, $gen_name)}(self.$conv_fn(), &mut buf.buf);
321+
assert!(Self::BITS <= $T::BITS, "need lossless conversion");
322+
offset = ${concat(_inner_slow_integer_to_str, $fmt_fn)}(*self as $T, &mut buf.buf);
346323
}
347324
// SAFETY: Starting from `offset`, all elements of the slice have been set.
348325
unsafe { slice_buffer_to_str(&buf.buf, offset) }
@@ -353,7 +330,7 @@ macro_rules! impl_Display {
353330
)*
354331

355332
#[cfg(feature = "optimize_for_size")]
356-
fn ${concat(_inner_slow_integer_to_str, $gen_name)}(mut n: $u, buf: &mut [MaybeUninit::<u8>]) -> usize {
333+
fn ${concat(_inner_slow_integer_to_str, $fmt_fn)}(mut n: $T, buf: &mut [MaybeUninit::<u8>]) -> usize {
357334
let mut curr = buf.len();
358335

359336
// SAFETY: To show that it's OK to copy into `buf_ptr`, notice that at the beginning
@@ -374,11 +351,11 @@ macro_rules! impl_Display {
374351
}
375352

376353
#[cfg(feature = "optimize_for_size")]
377-
fn $gen_name(n: $u, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result {
378-
const MAX_DEC_N: usize = $u::MAX.ilog(10) as usize + 1;
354+
fn $fmt_fn(n: $T, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355+
const MAX_DEC_N: usize = $T::MAX.ilog(10) as usize + 1;
379356
let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];
380357

381-
let offset = ${concat(_inner_slow_integer_to_str, $gen_name)}(n, &mut buf);
358+
let offset = ${concat(_inner_slow_integer_to_str, $fmt_fn)}(n, &mut buf);
382359
// SAFETY: Starting from `offset`, all elements of the slice have been set.
383360
let buf_slice = unsafe { slice_buffer_to_str(&buf, offset) };
384361
f.pad_integral(is_nonnegative, "", buf_slice)
@@ -387,9 +364,9 @@ macro_rules! impl_Display {
387364
}
388365

389366
macro_rules! impl_Exp {
390-
($($t:ident),*as $u:ident via $conv_fn:ident named $name:ident) => {
391-
fn $name(
392-
mut n: $u,
367+
($($Signed:ident, $Unsigned:ident),*;as $T:ident into $fmt_fn:ident) => {
368+
fn $fmt_fn(
369+
mut n: $T,
393370
is_nonnegative: bool,
394371
upper: bool,
395372
f: &mut fmt::Formatter<'_>
@@ -523,32 +500,41 @@ macro_rules! impl_Exp {
523500

524501
$(
525502
#[stable(feature = "integer_exp_format", since = "1.42.0")]
526-
impl fmt::LowerExp for $t {
527-
#[allow(unused_comparisons)]
503+
impl fmt::LowerExp for $Signed {
528504
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529505
let is_nonnegative = *self >= 0;
530506
let n = if is_nonnegative {
531-
self.$conv_fn()
507+
*selfas $T
532508
} else {
533-
// convert the negative num to positive by summing 1 to its 2s complement
534-
(!self.$conv_fn()).wrapping_add(1)
509+
self.unsigned_abs() as $T
535510
};
536-
$name(n, is_nonnegative, false, f)
511+
$fmt_fn(n, is_nonnegative, false, f)
512+
}
513+
}
514+
#[stable(feature = "integer_exp_format", since = "1.42.0")]
515+
impl fmt::LowerExp for $Unsigned {
516+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517+
$fmt_fn(*self as $T, true, false, f)
537518
}
538519
})*
520+
539521
$(
540522
#[stable(feature = "integer_exp_format", since = "1.42.0")]
541-
impl fmt::UpperExp for $t {
542-
#[allow(unused_comparisons)]
523+
impl fmt::UpperExp for $Signed {
543524
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544525
let is_nonnegative = *self >= 0;
545526
let n = if is_nonnegative {
546-
self.$conv_fn()
527+
*selfas $T
547528
} else {
548-
// convert the negative num to positive by summing 1 to its 2s complement
549-
(!self.$conv_fn()).wrapping_add(1)
529+
self.unsigned_abs() as $T
550530
};
551-
$name(n, is_nonnegative, true, f)
531+
$fmt_fn(n, is_nonnegative, true, f)
532+
}
533+
}
534+
#[stable(feature = "integer_exp_format", since = "1.42.0")]
535+
impl fmt::UpperExp for $Unsigned {
536+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537+
$fmt_fn(*self as $T, true, true, f)
552538
}
553539
})*
554540
};
@@ -564,37 +550,20 @@ impl_Debug! {
564550
#[cfg(any(target_pointer_width = "64", target_arch = "wasm32"))]
565551
mod imp {
566552
use super::*;
567-
impl_Display!(
568-
i8, u8,
569-
i16, u16,
570-
i32, u32,
571-
i64, u64,
572-
isize, usize,
573-
; as u64 via to_u64 named fmt_u64
574-
);
575-
impl_Exp!(
576-
i8, u8, i16, u16, i32, u32, i64, u64, usize, isize
577-
as u64 via to_u64 named exp_u64
578-
);
553+
impl_Display!(i8, u8, i16, u16, i32, u32, i64, u64, isize, usize; as u64 into fmt_u64);
554+
impl_Exp!(i8, u8, i16, u16, i32, u32, i64, u64, isize, usize; as u64 into exp_u64);
579555
}
580556

581557
#[cfg(not(any(target_pointer_width = "64", target_arch = "wasm32")))]
582558
mod imp {
583559
use super::*;
584-
impl_Display!(
585-
i8, u8,
586-
i16, u16,
587-
i32, u32,
588-
isize, usize,
589-
; as u32 via to_u32 named fmt_u32);
590-
impl_Display!(
591-
i64, u64,
592-
; as u64 via to_u64 named fmt_u64);
593-
594-
impl_Exp!(i8, u8, i16, u16, i32, u32, isize, usize as u32 via to_u32 named exp_u32);
595-
impl_Exp!(i64, u64 as u64 via to_u64 named exp_u64);
560+
impl_Display!(i8, u8, i16, u16, i32, u32, isize, usize; as u32 into fmt_u32);
561+
impl_Display!(i64, u64; as u64 into fmt_u64);
562+
563+
impl_Exp!(i8, u8, i16, u16, i32, u32, isize, usize; as u32 into exp_u32);
564+
impl_Exp!(i64, u64; as u64 into exp_u64);
596565
}
597-
impl_Exp!(i128, u128 as u128 via to_u128 named exp_u128);
566+
impl_Exp!(i128, u128; as u128 into exp_u128);
598567

599568
const U128_MAX_DEC_N: usize = u128::MAX.ilog10() as usize + 1;
600569

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /