Skip to main content

core/num/
mod.rs

1//! Numeric traits and functions for the built-in numeric types.
2
3#![stable(feature = "rust1", since = "1.0.0")]
4
5use crate::convert::{BoundedCastFromInt, CheckedCastFromInt};
6use crate::panic::const_panic;
7use crate::str::FromStr;
8use crate::ub_checks::assert_unsafe_precondition;
9use crate::{ascii, intrinsics, mem};
10
11// FIXME(const-hack): Used because the `?` operator is not allowed in a const context.
12macro_rules! try_opt {
13    ($e:expr) => {
14        match $e {
15            Some(x) => x,
16            None => return None,
17        }
18    };
19}
20
21// Use this when the generated code should differ between signed and unsigned types.
22macro_rules! sign_dependent_expr {
23    (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
24        $signed_case
25    };
26    (unsigned ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
27        $unsigned_case
28    };
29}
30
31// These modules are public only for testing.
32#[doc(hidden)]
33#[unstable(
34    feature = "num_internals",
35    reason = "internal routines only exposed for testing",
36    issue = "none"
37)]
38pub mod imp;
39
40#[macro_use]
41mod int_macros; // import int_impl!
42#[macro_use]
43mod uint_macros; // import uint_impl!
44
45mod error;
46#[cfg(not(no_fp_fmt_parse))]
47mod float_parse;
48mod nonzero;
49mod saturating;
50mod traits;
51mod wrapping;
52
53/// 100% perma-unstable
54#[doc(hidden)]
55pub mod niche_types;
56
57#[stable(feature = "int_error_matching", since = "1.55.0")]
58pub use error::IntErrorKind;
59#[stable(feature = "rust1", since = "1.0.0")]
60pub use error::ParseIntError;
61#[stable(feature = "try_from", since = "1.34.0")]
62pub use error::TryFromIntError;
63#[stable(feature = "rust1", since = "1.0.0")]
64#[cfg(not(no_fp_fmt_parse))]
65pub use float_parse::ParseFloatError;
66#[stable(feature = "generic_nonzero", since = "1.79.0")]
67pub use nonzero::NonZero;
68#[unstable(
69    feature = "nonzero_internals",
70    reason = "implementation detail which may disappear or be replaced at any time",
71    issue = "none"
72)]
73pub use nonzero::ZeroablePrimitive;
74#[stable(feature = "signed_nonzero", since = "1.34.0")]
75pub use nonzero::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize};
76#[stable(feature = "nonzero", since = "1.28.0")]
77pub use nonzero::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize};
78#[stable(feature = "saturating_int_impl", since = "1.74.0")]
79pub use saturating::Saturating;
80#[stable(feature = "rust1", since = "1.0.0")]
81pub use wrapping::Wrapping;
82
83macro_rules! u8_xe_bytes_doc {
84    () => {
85        "
86
87**Note**: This function is meaningless on `u8`. Byte order does not exist as a
88concept for byte-sized integers. This function is only provided in symmetry
89with larger integer types.
90
91"
92    };
93}
94
95macro_rules! i8_xe_bytes_doc {
96    () => {
97        "
98
99**Note**: This function is meaningless on `i8`. Byte order does not exist as a
100concept for byte-sized integers. This function is only provided in symmetry
101with larger integer types. You can cast from and to `u8` using
102[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
103
104"
105    };
106}
107
108macro_rules! usize_isize_to_xe_bytes_doc {
109    () => {
110        "
111
112**Note**: This function returns an array of length 2, 4 or 8 bytes
113depending on the target pointer size.
114
115"
116    };
117}
118
119macro_rules! usize_isize_from_xe_bytes_doc {
120    () => {
121        "
122
123**Note**: This function takes an array of length 2, 4 or 8 bytes
124depending on the target pointer size.
125
126"
127    };
128}
129
130macro_rules! midpoint_impl {
131    ($SelfT:ty, unsigned) => {
132        /// Calculates the midpoint (average) between `self` and `rhs`.
133        ///
134        /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
135        /// sufficiently-large unsigned integral type. This implies that the result is
136        /// always rounded towards zero and that no overflow will ever occur.
137        ///
138        /// # Examples
139        ///
140        /// ```
141        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
142        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".midpoint(4), 2);")]
143        /// ```
144        #[stable(feature = "num_midpoint", since = "1.85.0")]
145        #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
146        #[must_use = "this returns the result of the operation, \
147                      without modifying the original"]
148        #[doc(alias = "average_floor")]
149        #[doc(alias = "average")]
150        #[inline]
151        pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
152            // Use the well known branchless algorithm from Hacker's Delight to compute
153            // `(a + b) / 2` without overflowing: `((a ^ b) >> 1) + (a & b)`.
154            ((self ^ rhs) >> 1) + (self & rhs)
155        }
156    };
157    ($SelfT:ty, signed) => {
158        /// Calculates the midpoint (average) between `self` and `rhs`.
159        ///
160        /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
161        /// sufficiently-large signed integral type. This implies that the result is
162        /// always rounded towards zero and that no overflow will ever occur.
163        ///
164        /// # Examples
165        ///
166        /// ```
167        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
168        #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").midpoint(2), 0);")]
169        #[doc = concat!("assert_eq!((-7", stringify!($SelfT), ").midpoint(0), -3);")]
170        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(-7), -3);")]
171        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(7), 3);")]
172        /// ```
173        #[stable(feature = "num_midpoint_signed", since = "1.87.0")]
174        #[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
175        #[must_use = "this returns the result of the operation, \
176                      without modifying the original"]
177        #[doc(alias = "average_floor")]
178        #[doc(alias = "average_ceil")]
179        #[doc(alias = "average")]
180        #[inline]
181        pub const fn midpoint(self, rhs: Self) -> Self {
182            // Use the well known branchless algorithm from Hacker's Delight to compute
183            // `(a + b) / 2` without overflowing: `((a ^ b) >> 1) + (a & b)`.
184            let t = ((self ^ rhs) >> 1) + (self & rhs);
185            // Except that it fails for integers whose sum is an odd negative number as
186            // their floor is one less than their average. So we adjust the result.
187            t + (if t < 0 { 1 } else { 0 } & (self ^ rhs))
188        }
189    };
190    ($SelfT:ty, $WideT:ty, unsigned) => {
191        /// Calculates the midpoint (average) between `self` and `rhs`.
192        ///
193        /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
194        /// sufficiently-large unsigned integral type. This implies that the result is
195        /// always rounded towards zero and that no overflow will ever occur.
196        ///
197        /// # Examples
198        ///
199        /// ```
200        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
201        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".midpoint(4), 2);")]
202        /// ```
203        #[stable(feature = "num_midpoint", since = "1.85.0")]
204        #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
205        #[must_use = "this returns the result of the operation, \
206                      without modifying the original"]
207        #[doc(alias = "average_floor")]
208        #[doc(alias = "average")]
209        #[inline]
210        pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
211            ((self as $WideT + rhs as $WideT) / 2) as $SelfT
212        }
213    };
214    ($SelfT:ty, $WideT:ty, signed) => {
215        /// Calculates the midpoint (average) between `self` and `rhs`.
216        ///
217        /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
218        /// sufficiently-large signed integral type. This implies that the result is
219        /// always rounded towards zero and that no overflow will ever occur.
220        ///
221        /// # Examples
222        ///
223        /// ```
224        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
225        #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").midpoint(2), 0);")]
226        #[doc = concat!("assert_eq!((-7", stringify!($SelfT), ").midpoint(0), -3);")]
227        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(-7), -3);")]
228        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(7), 3);")]
229        /// ```
230        #[stable(feature = "num_midpoint_signed", since = "1.87.0")]
231        #[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
232        #[must_use = "this returns the result of the operation, \
233                      without modifying the original"]
234        #[doc(alias = "average_floor")]
235        #[doc(alias = "average_ceil")]
236        #[doc(alias = "average")]
237        #[inline]
238        pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
239            ((self as $WideT + rhs as $WideT) / 2) as $SelfT
240        }
241    };
242}
243
244macro_rules! widening_mul_impl {
245    ($SelfT:ty, $WideT:ty) => {
246        /// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
247        ///
248        /// The returned value is always exact and can never overflow.
249        ///
250        /// Note that this method is semantically equivalent to [`carrying_mul`] with a
251        /// carry of zero, with the latter instead returning a tuple denoting the low and
252        /// high parts of the result. Consider using it instead if you need
253        /// interoperability with other big int helper functions, or if this method isn't
254        /// available for a given type.
255        ///
256        /// [`carrying_mul`]: Self::carrying_mul
257        ///
258        /// # Examples
259        ///
260        /// ```
261        /// #![feature(widening_mul)]
262        ///
263        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_mul(0_", stringify!($SelfT), "), 0);")]
264        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_mul(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX as ", stringify!($WideT), " * ", stringify!($SelfT), "::MAX as ", stringify!($WideT), ");")]
265        /// ```
266        #[unstable(feature = "widening_mul", issue = "152016")]
267        #[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
268        #[must_use = "this returns the result of the operation, \
269                      without modifying the original"]
270        #[inline]
271        pub const fn widening_mul(self, rhs: Self) -> $WideT {
272            self as $WideT * rhs as $WideT
273        }
274    }
275}
276
277macro_rules! widening_carryless_mul_impl {
278    ($SelfT:ty, $WideT:ty) => {
279        /// Performs a widening carry-less multiplication.
280        ///
281        /// # Examples
282        ///
283        /// ```
284        /// #![feature(uint_carryless_mul)]
285        ///
286        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_carryless_mul(",
287                                stringify!($SelfT), "::MAX), ", stringify!($WideT), "::MAX / 3);")]
288        /// ```
289        #[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
290        #[doc(alias = "clmul")]
291        #[unstable(feature = "uint_carryless_mul", issue = "152080")]
292        #[must_use = "this returns the result of the operation, \
293                      without modifying the original"]
294        #[inline]
295        pub const fn widening_carryless_mul(self, rhs: $SelfT) -> $WideT {
296            (self as $WideT).carryless_mul(rhs as $WideT)
297        }
298    }
299}
300
301macro_rules! carrying_carryless_mul_impl {
302    (u128, u256) => {
303        carrying_carryless_mul_impl! { @internal u128 =>
304            pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
305                let x0 = self as u64;
306                let x1 = (self >> 64) as u64;
307                let y0 = rhs as u64;
308                let y1 = (rhs >> 64) as u64;
309
310                let z0 = u64::widening_carryless_mul(x0, y0);
311                let z2 = u64::widening_carryless_mul(x1, y1);
312
313                // The grade school algorithm would compute:
314                // z1 = x0y1 ^ x1y0
315
316                // Instead, Karatsuba first computes:
317                let z3 = u64::widening_carryless_mul(x0 ^ x1, y0 ^ y1);
318                // Since it distributes over XOR,
319                // z3 == x0y0 ^ x0y1 ^ x1y0 ^ x1y1
320                //       |--|   |---------|   |--|
321                //    ==  z0  ^     z1      ^  z2
322                // so we can compute z1 as
323                let z1 = z3 ^ z0 ^ z2;
324
325                let lo = z0 ^ (z1 << 64);
326                let hi = z2 ^ (z1 >> 64);
327
328                (lo ^ carry, hi)
329            }
330        }
331    };
332    ($SelfT:ty, $WideT:ty) => {
333        carrying_carryless_mul_impl! { @internal $SelfT =>
334            pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
335                // Can't use widening_carryless_mul because it's not implemented for usize.
336                let p = (self as $WideT).carryless_mul(rhs as $WideT);
337
338                let lo = (p as $SelfT);
339                let hi = (p  >> Self::BITS) as $SelfT;
340
341                (lo ^ carry, hi)
342            }
343        }
344    };
345    (@internal $SelfT:ty => $($fn:tt)*) => {
346        /// Calculates the "full carryless multiplication" without the possibility to overflow.
347        ///
348        /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
349        /// of the result as two separate values, in that order.
350        ///
351        /// # Examples
352        ///
353        /// Please note that this example is shared among integer types, which is why `u8` is used.
354        ///
355        /// ```
356        /// #![feature(uint_carryless_mul)]
357        ///
358        /// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b0000), (0, 0b0100_0000));
359        /// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b1111), (0b1111, 0b0100_0000));
360        #[doc = concat!("assert_eq!(",
361            stringify!($SelfT), "::MAX.carrying_carryless_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
362            "(!(", stringify!($SelfT), "::MAX / 3), ", stringify!($SelfT), "::MAX / 3));"
363        )]
364        /// ```
365        #[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
366        #[doc(alias = "clmul")]
367        #[unstable(feature = "uint_carryless_mul", issue = "152080")]
368        #[must_use = "this returns the result of the operation, \
369                      without modifying the original"]
370        #[inline]
371        $($fn)*
372    }
373}
374
375impl i8 {
376    int_impl! {
377        Self = i8,
378        ActualT = i8,
379        UnsignedT = u8,
380        BITS = 8,
381        BITS_MINUS_ONE = 7,
382        Min = -128,
383        Max = 127,
384        rot = 2,
385        rot_op = "-0x7e",
386        rot_result = "0xa",
387        swap_op = "0x12",
388        swapped = "0x12",
389        reversed = "0x48",
390        le_bytes = "[0x12]",
391        be_bytes = "[0x12]",
392        to_xe_bytes_doc = i8_xe_bytes_doc!(),
393        from_xe_bytes_doc = i8_xe_bytes_doc!(),
394        bound_condition = "",
395    }
396    midpoint_impl! { i8, i16, signed }
397    widening_mul_impl! { i8, i16 }
398}
399
400impl i16 {
401    int_impl! {
402        Self = i16,
403        ActualT = i16,
404        UnsignedT = u16,
405        BITS = 16,
406        BITS_MINUS_ONE = 15,
407        Min = -32768,
408        Max = 32767,
409        rot = 4,
410        rot_op = "-0x5ffd",
411        rot_result = "0x3a",
412        swap_op = "0x1234",
413        swapped = "0x3412",
414        reversed = "0x2c48",
415        le_bytes = "[0x34, 0x12]",
416        be_bytes = "[0x12, 0x34]",
417        to_xe_bytes_doc = "",
418        from_xe_bytes_doc = "",
419        bound_condition = "",
420    }
421    midpoint_impl! { i16, i32, signed }
422    widening_mul_impl! { i16, i32 }
423}
424
425impl i32 {
426    int_impl! {
427        Self = i32,
428        ActualT = i32,
429        UnsignedT = u32,
430        BITS = 32,
431        BITS_MINUS_ONE = 31,
432        Min = -2147483648,
433        Max = 2147483647,
434        rot = 8,
435        rot_op = "0x10000b3",
436        rot_result = "0xb301",
437        swap_op = "0x12345678",
438        swapped = "0x78563412",
439        reversed = "0x1e6a2c48",
440        le_bytes = "[0x78, 0x56, 0x34, 0x12]",
441        be_bytes = "[0x12, 0x34, 0x56, 0x78]",
442        to_xe_bytes_doc = "",
443        from_xe_bytes_doc = "",
444        bound_condition = "",
445    }
446    midpoint_impl! { i32, i64, signed }
447    widening_mul_impl! { i32, i64 }
448}
449
450impl i64 {
451    int_impl! {
452        Self = i64,
453        ActualT = i64,
454        UnsignedT = u64,
455        BITS = 64,
456        BITS_MINUS_ONE = 63,
457        Min = -9223372036854775808,
458        Max = 9223372036854775807,
459        rot = 12,
460        rot_op = "0xaa00000000006e1",
461        rot_result = "0x6e10aa",
462        swap_op = "0x1234567890123456",
463        swapped = "0x5634129078563412",
464        reversed = "0x6a2c48091e6a2c48",
465        le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
466        be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
467        to_xe_bytes_doc = "",
468        from_xe_bytes_doc = "",
469        bound_condition = "",
470    }
471    midpoint_impl! { i64, signed }
472    widening_mul_impl! { i64, i128 }
473}
474
475impl i128 {
476    int_impl! {
477        Self = i128,
478        ActualT = i128,
479        UnsignedT = u128,
480        BITS = 128,
481        BITS_MINUS_ONE = 127,
482        Min = -170141183460469231731687303715884105728,
483        Max = 170141183460469231731687303715884105727,
484        rot = 16,
485        rot_op = "0x13f40000000000000000000000004f76",
486        rot_result = "0x4f7613f4",
487        swap_op = "0x12345678901234567890123456789012",
488        swapped = "0x12907856341290785634129078563412",
489        reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
490        le_bytes = "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
491            0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
492        be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
493            0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
494        to_xe_bytes_doc = "",
495        from_xe_bytes_doc = "",
496        bound_condition = "",
497    }
498    midpoint_impl! { i128, signed }
499}
500
501#[doc(auto_cfg = false)]
502#[cfg(target_pointer_width = "16")]
503impl isize {
504    int_impl! {
505        Self = isize,
506        ActualT = i16,
507        UnsignedT = usize,
508        BITS = 16,
509        BITS_MINUS_ONE = 15,
510        Min = -32768,
511        Max = 32767,
512        rot = 4,
513        rot_op = "-0x5ffd",
514        rot_result = "0x3a",
515        swap_op = "0x1234",
516        swapped = "0x3412",
517        reversed = "0x2c48",
518        le_bytes = "[0x34, 0x12]",
519        be_bytes = "[0x12, 0x34]",
520        to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
521        from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
522        bound_condition = " on 16-bit targets",
523    }
524    midpoint_impl! { isize, i32, signed }
525}
526
527#[doc(auto_cfg = false)]
528#[cfg(target_pointer_width = "32")]
529impl isize {
530    int_impl! {
531        Self = isize,
532        ActualT = i32,
533        UnsignedT = usize,
534        BITS = 32,
535        BITS_MINUS_ONE = 31,
536        Min = -2147483648,
537        Max = 2147483647,
538        rot = 8,
539        rot_op = "0x10000b3",
540        rot_result = "0xb301",
541        swap_op = "0x12345678",
542        swapped = "0x78563412",
543        reversed = "0x1e6a2c48",
544        le_bytes = "[0x78, 0x56, 0x34, 0x12]",
545        be_bytes = "[0x12, 0x34, 0x56, 0x78]",
546        to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
547        from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
548        bound_condition = " on 32-bit targets",
549    }
550    midpoint_impl! { isize, i64, signed }
551}
552
553#[doc(auto_cfg = false)]
554#[cfg(target_pointer_width = "64")]
555impl isize {
556    int_impl! {
557        Self = isize,
558        ActualT = i64,
559        UnsignedT = usize,
560        BITS = 64,
561        BITS_MINUS_ONE = 63,
562        Min = -9223372036854775808,
563        Max = 9223372036854775807,
564        rot = 12,
565        rot_op = "0xaa00000000006e1",
566        rot_result = "0x6e10aa",
567        swap_op = "0x1234567890123456",
568        swapped = "0x5634129078563412",
569        reversed = "0x6a2c48091e6a2c48",
570        le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
571        be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
572        to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
573        from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
574        bound_condition = " on 64-bit targets",
575    }
576    midpoint_impl! { isize, signed }
577}
578
579/// If the bit selected by this mask is set, ascii is lower case.
580const ASCII_CASE_MASK: u8 = 0b0010_0000;
581
582impl u8 {
583    uint_impl! {
584        Self = u8,
585        ActualT = u8,
586        SignedT = i8,
587        BITS = 8,
588        BITS_MINUS_ONE = 7,
589        MAX = 255,
590        rot = 2,
591        rot_op = "0x82",
592        rot_result = "0xa",
593        fsh_op = "0x36",
594        fshl_result = "0x8",
595        fshr_result = "0x8d",
596        clmul_lhs = "0x12",
597        clmul_rhs = "0x34",
598        clmul_result = "0x28",
599        swap_op = "0x12",
600        swapped = "0x12",
601        reversed = "0x48",
602        le_bytes = "[0x12]",
603        be_bytes = "[0x12]",
604        to_xe_bytes_doc = u8_xe_bytes_doc!(),
605        from_xe_bytes_doc = u8_xe_bytes_doc!(),
606        bound_condition = "",
607    }
608    midpoint_impl! { u8, u16, unsigned }
609    widening_mul_impl! { u8, u16 }
610    widening_carryless_mul_impl! { u8, u16 }
611    carrying_carryless_mul_impl! { u8, u16 }
612
613    /// Checks if the value is within the ASCII range.
614    ///
615    /// # Examples
616    ///
617    /// ```
618    /// let ascii = 97u8;
619    /// let non_ascii = 150u8;
620    ///
621    /// assert!(ascii.is_ascii());
622    /// assert!(!non_ascii.is_ascii());
623    /// ```
624    #[must_use]
625    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
626    #[rustc_const_stable(feature = "const_u8_is_ascii", since = "1.43.0")]
627    #[inline]
628    pub const fn is_ascii(&self) -> bool {
629        *self <= 127
630    }
631
632    /// If the value of this byte is within the ASCII range, returns it as an
633    /// [ASCII character](ascii::Char).  Otherwise, returns `None`.
634    #[must_use]
635    #[unstable(feature = "ascii_char", issue = "110998")]
636    #[inline]
637    pub const fn as_ascii(&self) -> Option<ascii::Char> {
638        ascii::Char::from_u8(*self)
639    }
640
641    /// Converts this byte to an [ASCII character](ascii::Char), without
642    /// checking whether or not it's valid.
643    ///
644    /// # Safety
645    ///
646    /// This byte must be valid ASCII, or else this is UB.
647    #[must_use]
648    #[unstable(feature = "ascii_char", issue = "110998")]
649    #[inline]
650    pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
651        assert_unsafe_precondition!(
652            check_library_ub,
653            "as_ascii_unchecked requires that the byte is valid ASCII",
654            (it: &u8 = self) => it.is_ascii()
655        );
656
657        // SAFETY: the caller promised that this byte is ASCII.
658        unsafe { ascii::Char::from_u8_unchecked(*self) }
659    }
660
661    /// Makes a copy of the value in its ASCII upper case equivalent.
662    ///
663    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
664    /// but non-ASCII letters are unchanged.
665    ///
666    /// To uppercase the value in-place, use [`make_ascii_uppercase`].
667    ///
668    /// # Examples
669    ///
670    /// ```
671    /// let lowercase_a = 97u8;
672    ///
673    /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
674    /// ```
675    ///
676    /// [`make_ascii_uppercase`]: Self::make_ascii_uppercase
677    #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
678    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
679    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
680    #[inline]
681    pub const fn to_ascii_uppercase(&self) -> u8 {
682        // Toggle the 6th bit if this is a lowercase letter
683        *self ^ ((self.is_ascii_lowercase() as u8) * ASCII_CASE_MASK)
684    }
685
686    /// Makes a copy of the value in its ASCII lower case equivalent.
687    ///
688    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
689    /// but non-ASCII letters are unchanged.
690    ///
691    /// To lowercase the value in-place, use [`make_ascii_lowercase`].
692    ///
693    /// # Examples
694    ///
695    /// ```
696    /// let uppercase_a = 65u8;
697    ///
698    /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
699    /// ```
700    ///
701    /// [`make_ascii_lowercase`]: Self::make_ascii_lowercase
702    #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
703    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
704    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
705    #[inline]
706    pub const fn to_ascii_lowercase(&self) -> u8 {
707        // Set the 6th bit if this is an uppercase letter
708        *self | (self.is_ascii_uppercase() as u8 * ASCII_CASE_MASK)
709    }
710
711    /// Assumes self is ascii
712    #[inline]
713    pub(crate) const fn ascii_change_case_unchecked(&self) -> u8 {
714        *self ^ ASCII_CASE_MASK
715    }
716
717    /// Checks that two values are an ASCII case-insensitive match.
718    ///
719    /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
720    ///
721    /// # Examples
722    ///
723    /// ```
724    /// let lowercase_a = 97u8;
725    /// let uppercase_a = 65u8;
726    ///
727    /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
728    /// ```
729    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
730    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
731    #[inline]
732    pub const fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
733        self.to_ascii_lowercase() == other.to_ascii_lowercase()
734    }
735
736    /// Converts this value to its ASCII upper case equivalent in-place.
737    ///
738    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
739    /// but non-ASCII letters are unchanged.
740    ///
741    /// To return a new uppercased value without modifying the existing one, use
742    /// [`to_ascii_uppercase`].
743    ///
744    /// # Examples
745    ///
746    /// ```
747    /// let mut byte = b'a';
748    ///
749    /// byte.make_ascii_uppercase();
750    ///
751    /// assert_eq!(b'A', byte);
752    /// ```
753    ///
754    /// [`to_ascii_uppercase`]: Self::to_ascii_uppercase
755    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
756    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
757    #[inline]
758    pub const fn make_ascii_uppercase(&mut self) {
759        *self = self.to_ascii_uppercase();
760    }
761
762    /// Converts this value to its ASCII lower case equivalent in-place.
763    ///
764    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
765    /// but non-ASCII letters are unchanged.
766    ///
767    /// To return a new lowercased value without modifying the existing one, use
768    /// [`to_ascii_lowercase`].
769    ///
770    /// # Examples
771    ///
772    /// ```
773    /// let mut byte = b'A';
774    ///
775    /// byte.make_ascii_lowercase();
776    ///
777    /// assert_eq!(b'a', byte);
778    /// ```
779    ///
780    /// [`to_ascii_lowercase`]: Self::to_ascii_lowercase
781    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
782    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
783    #[inline]
784    pub const fn make_ascii_lowercase(&mut self) {
785        *self = self.to_ascii_lowercase();
786    }
787
788    /// Checks if the value is an ASCII alphabetic character:
789    ///
790    /// - U+0041 'A' ..= U+005A 'Z', or
791    /// - U+0061 'a' ..= U+007A 'z'.
792    ///
793    /// # Examples
794    ///
795    /// ```
796    /// let uppercase_a = b'A';
797    /// let uppercase_g = b'G';
798    /// let a = b'a';
799    /// let g = b'g';
800    /// let zero = b'0';
801    /// let percent = b'%';
802    /// let space = b' ';
803    /// let lf = b'\n';
804    /// let esc = b'\x1b';
805    ///
806    /// assert!(uppercase_a.is_ascii_alphabetic());
807    /// assert!(uppercase_g.is_ascii_alphabetic());
808    /// assert!(a.is_ascii_alphabetic());
809    /// assert!(g.is_ascii_alphabetic());
810    /// assert!(!zero.is_ascii_alphabetic());
811    /// assert!(!percent.is_ascii_alphabetic());
812    /// assert!(!space.is_ascii_alphabetic());
813    /// assert!(!lf.is_ascii_alphabetic());
814    /// assert!(!esc.is_ascii_alphabetic());
815    /// ```
816    #[must_use]
817    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
818    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
819    #[inline]
820    pub const fn is_ascii_alphabetic(&self) -> bool {
821        matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
822    }
823
824    /// Checks if the value is an ASCII uppercase character:
825    /// U+0041 'A' ..= U+005A 'Z'.
826    ///
827    /// # Examples
828    ///
829    /// ```
830    /// let uppercase_a = b'A';
831    /// let uppercase_g = b'G';
832    /// let a = b'a';
833    /// let g = b'g';
834    /// let zero = b'0';
835    /// let percent = b'%';
836    /// let space = b' ';
837    /// let lf = b'\n';
838    /// let esc = b'\x1b';
839    ///
840    /// assert!(uppercase_a.is_ascii_uppercase());
841    /// assert!(uppercase_g.is_ascii_uppercase());
842    /// assert!(!a.is_ascii_uppercase());
843    /// assert!(!g.is_ascii_uppercase());
844    /// assert!(!zero.is_ascii_uppercase());
845    /// assert!(!percent.is_ascii_uppercase());
846    /// assert!(!space.is_ascii_uppercase());
847    /// assert!(!lf.is_ascii_uppercase());
848    /// assert!(!esc.is_ascii_uppercase());
849    /// ```
850    #[must_use]
851    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
852    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
853    #[inline]
854    pub const fn is_ascii_uppercase(&self) -> bool {
855        matches!(*self, b'A'..=b'Z')
856    }
857
858    /// Checks if the value is an ASCII lowercase character:
859    /// U+0061 'a' ..= U+007A 'z'.
860    ///
861    /// # Examples
862    ///
863    /// ```
864    /// let uppercase_a = b'A';
865    /// let uppercase_g = b'G';
866    /// let a = b'a';
867    /// let g = b'g';
868    /// let zero = b'0';
869    /// let percent = b'%';
870    /// let space = b' ';
871    /// let lf = b'\n';
872    /// let esc = b'\x1b';
873    ///
874    /// assert!(!uppercase_a.is_ascii_lowercase());
875    /// assert!(!uppercase_g.is_ascii_lowercase());
876    /// assert!(a.is_ascii_lowercase());
877    /// assert!(g.is_ascii_lowercase());
878    /// assert!(!zero.is_ascii_lowercase());
879    /// assert!(!percent.is_ascii_lowercase());
880    /// assert!(!space.is_ascii_lowercase());
881    /// assert!(!lf.is_ascii_lowercase());
882    /// assert!(!esc.is_ascii_lowercase());
883    /// ```
884    #[must_use]
885    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
886    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
887    #[inline]
888    pub const fn is_ascii_lowercase(&self) -> bool {
889        matches!(*self, b'a'..=b'z')
890    }
891
892    /// Checks if the value is an ASCII alphanumeric character:
893    ///
894    /// - U+0041 'A' ..= U+005A 'Z', or
895    /// - U+0061 'a' ..= U+007A 'z', or
896    /// - U+0030 '0' ..= U+0039 '9'.
897    ///
898    /// # Examples
899    ///
900    /// ```
901    /// let uppercase_a = b'A';
902    /// let uppercase_g = b'G';
903    /// let a = b'a';
904    /// let g = b'g';
905    /// let zero = b'0';
906    /// let percent = b'%';
907    /// let space = b' ';
908    /// let lf = b'\n';
909    /// let esc = b'\x1b';
910    ///
911    /// assert!(uppercase_a.is_ascii_alphanumeric());
912    /// assert!(uppercase_g.is_ascii_alphanumeric());
913    /// assert!(a.is_ascii_alphanumeric());
914    /// assert!(g.is_ascii_alphanumeric());
915    /// assert!(zero.is_ascii_alphanumeric());
916    /// assert!(!percent.is_ascii_alphanumeric());
917    /// assert!(!space.is_ascii_alphanumeric());
918    /// assert!(!lf.is_ascii_alphanumeric());
919    /// assert!(!esc.is_ascii_alphanumeric());
920    /// ```
921    #[must_use]
922    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
923    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
924    #[inline]
925    pub const fn is_ascii_alphanumeric(&self) -> bool {
926        matches!(*self, b'0'..=b'9') | matches!(*self, b'A'..=b'Z') | matches!(*self, b'a'..=b'z')
927    }
928
929    /// Checks if the value is an ASCII decimal digit:
930    /// U+0030 '0' ..= U+0039 '9'.
931    ///
932    /// # Examples
933    ///
934    /// ```
935    /// let uppercase_a = b'A';
936    /// let uppercase_g = b'G';
937    /// let a = b'a';
938    /// let g = b'g';
939    /// let zero = b'0';
940    /// let percent = b'%';
941    /// let space = b' ';
942    /// let lf = b'\n';
943    /// let esc = b'\x1b';
944    ///
945    /// assert!(!uppercase_a.is_ascii_digit());
946    /// assert!(!uppercase_g.is_ascii_digit());
947    /// assert!(!a.is_ascii_digit());
948    /// assert!(!g.is_ascii_digit());
949    /// assert!(zero.is_ascii_digit());
950    /// assert!(!percent.is_ascii_digit());
951    /// assert!(!space.is_ascii_digit());
952    /// assert!(!lf.is_ascii_digit());
953    /// assert!(!esc.is_ascii_digit());
954    /// ```
955    #[must_use]
956    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
957    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
958    #[inline]
959    pub const fn is_ascii_digit(&self) -> bool {
960        matches!(*self, b'0'..=b'9')
961    }
962
963    /// Checks if the value is an ASCII octal digit:
964    /// U+0030 '0' ..= U+0037 '7'.
965    ///
966    /// # Examples
967    ///
968    /// ```
969    /// #![feature(is_ascii_octdigit)]
970    ///
971    /// let uppercase_a = b'A';
972    /// let a = b'a';
973    /// let zero = b'0';
974    /// let seven = b'7';
975    /// let nine = b'9';
976    /// let percent = b'%';
977    /// let lf = b'\n';
978    ///
979    /// assert!(!uppercase_a.is_ascii_octdigit());
980    /// assert!(!a.is_ascii_octdigit());
981    /// assert!(zero.is_ascii_octdigit());
982    /// assert!(seven.is_ascii_octdigit());
983    /// assert!(!nine.is_ascii_octdigit());
984    /// assert!(!percent.is_ascii_octdigit());
985    /// assert!(!lf.is_ascii_octdigit());
986    /// ```
987    #[must_use]
988    #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
989    #[inline]
990    pub const fn is_ascii_octdigit(&self) -> bool {
991        matches!(*self, b'0'..=b'7')
992    }
993
994    /// Checks if the value is an ASCII hexadecimal digit:
995    ///
996    /// - U+0030 '0' ..= U+0039 '9', or
997    /// - U+0041 'A' ..= U+0046 'F', or
998    /// - U+0061 'a' ..= U+0066 'f'.
999    ///
1000    /// # Examples
1001    ///
1002    /// ```
1003    /// let uppercase_a = b'A';
1004    /// let uppercase_g = b'G';
1005    /// let a = b'a';
1006    /// let g = b'g';
1007    /// let zero = b'0';
1008    /// let percent = b'%';
1009    /// let space = b' ';
1010    /// let lf = b'\n';
1011    /// let esc = b'\x1b';
1012    ///
1013    /// assert!(uppercase_a.is_ascii_hexdigit());
1014    /// assert!(!uppercase_g.is_ascii_hexdigit());
1015    /// assert!(a.is_ascii_hexdigit());
1016    /// assert!(!g.is_ascii_hexdigit());
1017    /// assert!(zero.is_ascii_hexdigit());
1018    /// assert!(!percent.is_ascii_hexdigit());
1019    /// assert!(!space.is_ascii_hexdigit());
1020    /// assert!(!lf.is_ascii_hexdigit());
1021    /// assert!(!esc.is_ascii_hexdigit());
1022    /// ```
1023    #[must_use]
1024    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1025    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1026    #[inline]
1027    pub const fn is_ascii_hexdigit(&self) -> bool {
1028        matches!(*self, b'0'..=b'9') | matches!(*self, b'A'..=b'F') | matches!(*self, b'a'..=b'f')
1029    }
1030
1031    /// Checks if the value is an ASCII punctuation or symbol character
1032    /// (i.e. not alphanumeric, whitespace, or control):
1033    ///
1034    /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1035    /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1036    /// - U+005B ..= U+0060 `` [ \ ] ^ _ ` ``, or
1037    /// - U+007B ..= U+007E `{ | } ~`
1038    ///
1039    /// # Examples
1040    ///
1041    /// ```
1042    /// let uppercase_a = b'A';
1043    /// let uppercase_g = b'G';
1044    /// let a = b'a';
1045    /// let g = b'g';
1046    /// let zero = b'0';
1047    /// let percent = b'%';
1048    /// let space = b' ';
1049    /// let lf = b'\n';
1050    /// let esc = b'\x1b';
1051    ///
1052    /// assert!(!uppercase_a.is_ascii_punctuation());
1053    /// assert!(!uppercase_g.is_ascii_punctuation());
1054    /// assert!(!a.is_ascii_punctuation());
1055    /// assert!(!g.is_ascii_punctuation());
1056    /// assert!(!zero.is_ascii_punctuation());
1057    /// assert!(percent.is_ascii_punctuation());
1058    /// assert!(!space.is_ascii_punctuation());
1059    /// assert!(!lf.is_ascii_punctuation());
1060    /// assert!(!esc.is_ascii_punctuation());
1061    /// ```
1062    #[must_use]
1063    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1064    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1065    #[inline]
1066    pub const fn is_ascii_punctuation(&self) -> bool {
1067        matches!(*self, b'!'..=b'/')
1068            | matches!(*self, b':'..=b'@')
1069            | matches!(*self, b'['..=b'`')
1070            | matches!(*self, b'{'..=b'~')
1071    }
1072
1073    /// Checks if the value is an ASCII graphic character
1074    /// (i.e. not whitespace or control):
1075    /// U+0021 '!' ..= U+007E '~'.
1076    ///
1077    /// # Examples
1078    ///
1079    /// ```
1080    /// let uppercase_a = b'A';
1081    /// let uppercase_g = b'G';
1082    /// let a = b'a';
1083    /// let g = b'g';
1084    /// let zero = b'0';
1085    /// let percent = b'%';
1086    /// let space = b' ';
1087    /// let lf = b'\n';
1088    /// let esc = b'\x1b';
1089    ///
1090    /// assert!(uppercase_a.is_ascii_graphic());
1091    /// assert!(uppercase_g.is_ascii_graphic());
1092    /// assert!(a.is_ascii_graphic());
1093    /// assert!(g.is_ascii_graphic());
1094    /// assert!(zero.is_ascii_graphic());
1095    /// assert!(percent.is_ascii_graphic());
1096    /// assert!(!space.is_ascii_graphic());
1097    /// assert!(!lf.is_ascii_graphic());
1098    /// assert!(!esc.is_ascii_graphic());
1099    /// ```
1100    #[must_use]
1101    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1102    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1103    #[inline]
1104    pub const fn is_ascii_graphic(&self) -> bool {
1105        matches!(*self, b'!'..=b'~')
1106    }
1107
1108    /// Checks if the value is an ASCII whitespace character:
1109    /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1110    /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1111    ///
1112    /// **Warning:** Because the list above excludes U+000B VERTICAL TAB,
1113    /// `b.is_ascii_whitespace()` is **not** equivalent to `char::from(b).is_whitespace()`.
1114    ///
1115    /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1116    /// whitespace][infra-aw]. There are several other definitions in
1117    /// wide use. For instance, [the POSIX locale][pct] includes
1118    /// U+000B VERTICAL TAB as well as all the above characters,
1119    /// but—from the very same specification—[the default rule for
1120    /// "field splitting" in the Bourne shell][bfs] considers *only*
1121    /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1122    ///
1123    /// If you are writing a program that will process an existing
1124    /// file format, check what that format's definition of whitespace is
1125    /// before using this function.
1126    ///
1127    /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1128    /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1129    /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1130    ///
1131    /// # Examples
1132    ///
1133    /// ```
1134    /// let uppercase_a = b'A';
1135    /// let uppercase_g = b'G';
1136    /// let a = b'a';
1137    /// let g = b'g';
1138    /// let zero = b'0';
1139    /// let percent = b'%';
1140    /// let space = b' ';
1141    /// let lf = b'\n';
1142    /// let esc = b'\x1b';
1143    ///
1144    /// assert!(!uppercase_a.is_ascii_whitespace());
1145    /// assert!(!uppercase_g.is_ascii_whitespace());
1146    /// assert!(!a.is_ascii_whitespace());
1147    /// assert!(!g.is_ascii_whitespace());
1148    /// assert!(!zero.is_ascii_whitespace());
1149    /// assert!(!percent.is_ascii_whitespace());
1150    /// assert!(space.is_ascii_whitespace());
1151    /// assert!(lf.is_ascii_whitespace());
1152    /// assert!(!esc.is_ascii_whitespace());
1153    /// ```
1154    #[must_use]
1155    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1156    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1157    #[inline]
1158    pub const fn is_ascii_whitespace(&self) -> bool {
1159        matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
1160    }
1161
1162    /// Checks if the value is an ASCII control character:
1163    /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1164    /// Note that most ASCII whitespace characters are control
1165    /// characters, but SPACE is not.
1166    ///
1167    /// # Examples
1168    ///
1169    /// ```
1170    /// let uppercase_a = b'A';
1171    /// let uppercase_g = b'G';
1172    /// let a = b'a';
1173    /// let g = b'g';
1174    /// let zero = b'0';
1175    /// let percent = b'%';
1176    /// let space = b' ';
1177    /// let lf = b'\n';
1178    /// let esc = b'\x1b';
1179    ///
1180    /// assert!(!uppercase_a.is_ascii_control());
1181    /// assert!(!uppercase_g.is_ascii_control());
1182    /// assert!(!a.is_ascii_control());
1183    /// assert!(!g.is_ascii_control());
1184    /// assert!(!zero.is_ascii_control());
1185    /// assert!(!percent.is_ascii_control());
1186    /// assert!(!space.is_ascii_control());
1187    /// assert!(lf.is_ascii_control());
1188    /// assert!(esc.is_ascii_control());
1189    /// ```
1190    #[must_use]
1191    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1192    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1193    #[inline]
1194    pub const fn is_ascii_control(&self) -> bool {
1195        matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
1196    }
1197
1198    /// Returns an iterator that produces an escaped version of a `u8`,
1199    /// treating it as an ASCII character.
1200    ///
1201    /// The behavior is identical to [`ascii::escape_default`].
1202    ///
1203    /// # Examples
1204    ///
1205    /// ```
1206    /// assert_eq!("0", b'0'.escape_ascii().to_string());
1207    /// assert_eq!("\\t", b'\t'.escape_ascii().to_string());
1208    /// assert_eq!("\\r", b'\r'.escape_ascii().to_string());
1209    /// assert_eq!("\\n", b'\n'.escape_ascii().to_string());
1210    /// assert_eq!("\\'", b'\''.escape_ascii().to_string());
1211    /// assert_eq!("\\\"", b'"'.escape_ascii().to_string());
1212    /// assert_eq!("\\\\", b'\\'.escape_ascii().to_string());
1213    /// assert_eq!("\\x9d", b'\x9d'.escape_ascii().to_string());
1214    /// ```
1215    #[must_use = "this returns the escaped byte as an iterator, \
1216                  without modifying the original"]
1217    #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
1218    #[inline]
1219    pub fn escape_ascii(self) -> ascii::EscapeDefault {
1220        ascii::escape_default(self)
1221    }
1222
1223    #[inline]
1224    pub(crate) const fn is_utf8_char_boundary(self) -> bool {
1225        // This is bit magic equivalent to: b < 128 || b >= 192
1226        (self as i8) >= -0x40
1227    }
1228}
1229
1230impl u16 {
1231    uint_impl! {
1232        Self = u16,
1233        ActualT = u16,
1234        SignedT = i16,
1235        BITS = 16,
1236        BITS_MINUS_ONE = 15,
1237        MAX = 65535,
1238        rot = 4,
1239        rot_op = "0xa003",
1240        rot_result = "0x3a",
1241        fsh_op = "0x2de",
1242        fshl_result = "0x30",
1243        fshr_result = "0x302d",
1244        clmul_lhs = "0x9012",
1245        clmul_rhs = "0xcd34",
1246        clmul_result = "0x928",
1247        swap_op = "0x1234",
1248        swapped = "0x3412",
1249        reversed = "0x2c48",
1250        le_bytes = "[0x34, 0x12]",
1251        be_bytes = "[0x12, 0x34]",
1252        to_xe_bytes_doc = "",
1253        from_xe_bytes_doc = "",
1254        bound_condition = "",
1255    }
1256    midpoint_impl! { u16, u32, unsigned }
1257    widening_mul_impl! { u16, u32 }
1258    widening_carryless_mul_impl! { u16, u32 }
1259    carrying_carryless_mul_impl! { u16, u32 }
1260
1261    /// Checks if the value is a Unicode surrogate code point, which are disallowed values for [`char`].
1262    ///
1263    /// # Examples
1264    ///
1265    /// ```
1266    /// #![feature(utf16_extra)]
1267    ///
1268    /// let low_non_surrogate = 0xA000u16;
1269    /// let low_surrogate = 0xD800u16;
1270    /// let high_surrogate = 0xDC00u16;
1271    /// let high_non_surrogate = 0xE000u16;
1272    ///
1273    /// assert!(!low_non_surrogate.is_utf16_surrogate());
1274    /// assert!(low_surrogate.is_utf16_surrogate());
1275    /// assert!(high_surrogate.is_utf16_surrogate());
1276    /// assert!(!high_non_surrogate.is_utf16_surrogate());
1277    /// ```
1278    #[must_use]
1279    #[unstable(feature = "utf16_extra", issue = "94919")]
1280    #[inline]
1281    pub const fn is_utf16_surrogate(self) -> bool {
1282        matches!(self, 0xD800..=0xDFFF)
1283    }
1284}
1285
1286impl u32 {
1287    uint_impl! {
1288        Self = u32,
1289        ActualT = u32,
1290        SignedT = i32,
1291        BITS = 32,
1292        BITS_MINUS_ONE = 31,
1293        MAX = 4294967295,
1294        rot = 8,
1295        rot_op = "0x10000b3",
1296        rot_result = "0xb301",
1297        fsh_op = "0x2fe78e45",
1298        fshl_result = "0xb32f",
1299        fshr_result = "0xb32fe78e",
1300        clmul_lhs = "0x56789012",
1301        clmul_rhs = "0xf52ecd34",
1302        clmul_result = "0x9b980928",
1303        swap_op = "0x12345678",
1304        swapped = "0x78563412",
1305        reversed = "0x1e6a2c48",
1306        le_bytes = "[0x78, 0x56, 0x34, 0x12]",
1307        be_bytes = "[0x12, 0x34, 0x56, 0x78]",
1308        to_xe_bytes_doc = "",
1309        from_xe_bytes_doc = "",
1310        bound_condition = "",
1311    }
1312    midpoint_impl! { u32, u64, unsigned }
1313    widening_mul_impl! { u32, u64 }
1314    widening_carryless_mul_impl! { u32, u64 }
1315    carrying_carryless_mul_impl! { u32, u64 }
1316}
1317
1318impl u64 {
1319    uint_impl! {
1320        Self = u64,
1321        ActualT = u64,
1322        SignedT = i64,
1323        BITS = 64,
1324        BITS_MINUS_ONE = 63,
1325        MAX = 18446744073709551615,
1326        rot = 12,
1327        rot_op = "0xaa00000000006e1",
1328        rot_result = "0x6e10aa",
1329        fsh_op = "0x2fe78e45983acd98",
1330        fshl_result = "0x6e12fe",
1331        fshr_result = "0x6e12fe78e45983ac",
1332        clmul_lhs = "0x7890123456789012",
1333        clmul_rhs = "0xdd358416f52ecd34",
1334        clmul_result = "0xa6299579b980928",
1335        swap_op = "0x1234567890123456",
1336        swapped = "0x5634129078563412",
1337        reversed = "0x6a2c48091e6a2c48",
1338        le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1339        be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
1340        to_xe_bytes_doc = "",
1341        from_xe_bytes_doc = "",
1342        bound_condition = "",
1343    }
1344    midpoint_impl! { u64, u128, unsigned }
1345    widening_mul_impl! { u64, u128 }
1346    widening_carryless_mul_impl! { u64, u128 }
1347    carrying_carryless_mul_impl! { u64, u128 }
1348}
1349
1350impl u128 {
1351    uint_impl! {
1352        Self = u128,
1353        ActualT = u128,
1354        SignedT = i128,
1355        BITS = 128,
1356        BITS_MINUS_ONE = 127,
1357        MAX = 340282366920938463463374607431768211455,
1358        rot = 16,
1359        rot_op = "0x13f40000000000000000000000004f76",
1360        rot_result = "0x4f7613f4",
1361        fsh_op = "0x2fe78e45983acd98039000008736273",
1362        fshl_result = "0x4f7602fe",
1363        fshr_result = "0x4f7602fe78e45983acd9803900000873",
1364        clmul_lhs = "0x12345678901234567890123456789012",
1365        clmul_rhs = "0x4317e40ab4ddcf05dd358416f52ecd34",
1366        clmul_result = "0xb9cf660de35d0c170a6299579b980928",
1367        swap_op = "0x12345678901234567890123456789012",
1368        swapped = "0x12907856341290785634129078563412",
1369        reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
1370        le_bytes = "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
1371            0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1372        be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
1373            0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
1374        to_xe_bytes_doc = "",
1375        from_xe_bytes_doc = "",
1376        bound_condition = "",
1377    }
1378    midpoint_impl! { u128, unsigned }
1379    carrying_carryless_mul_impl! { u128, u256 }
1380}
1381
1382#[doc(auto_cfg = false)]
1383#[cfg(target_pointer_width = "16")]
1384impl usize {
1385    uint_impl! {
1386        Self = usize,
1387        ActualT = u16,
1388        SignedT = isize,
1389        BITS = 16,
1390        BITS_MINUS_ONE = 15,
1391        MAX = 65535,
1392        rot = 4,
1393        rot_op = "0xa003",
1394        rot_result = "0x3a",
1395        fsh_op = "0x2de",
1396        fshl_result = "0x30",
1397        fshr_result = "0x302d",
1398        clmul_lhs = "0x9012",
1399        clmul_rhs = "0xcd34",
1400        clmul_result = "0x928",
1401        swap_op = "0x1234",
1402        swapped = "0x3412",
1403        reversed = "0x2c48",
1404        le_bytes = "[0x34, 0x12]",
1405        be_bytes = "[0x12, 0x34]",
1406        to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1407        from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1408        bound_condition = " on 16-bit targets",
1409    }
1410    midpoint_impl! { usize, u32, unsigned }
1411    carrying_carryless_mul_impl! { usize, u32 }
1412}
1413
1414#[doc(auto_cfg = false)]
1415#[cfg(target_pointer_width = "32")]
1416impl usize {
1417    uint_impl! {
1418        Self = usize,
1419        ActualT = u32,
1420        SignedT = isize,
1421        BITS = 32,
1422        BITS_MINUS_ONE = 31,
1423        MAX = 4294967295,
1424        rot = 8,
1425        rot_op = "0x10000b3",
1426        rot_result = "0xb301",
1427        fsh_op = "0x2fe78e45",
1428        fshl_result = "0xb32f",
1429        fshr_result = "0xb32fe78e",
1430        clmul_lhs = "0x56789012",
1431        clmul_rhs = "0xf52ecd34",
1432        clmul_result = "0x9b980928",
1433        swap_op = "0x12345678",
1434        swapped = "0x78563412",
1435        reversed = "0x1e6a2c48",
1436        le_bytes = "[0x78, 0x56, 0x34, 0x12]",
1437        be_bytes = "[0x12, 0x34, 0x56, 0x78]",
1438        to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1439        from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1440        bound_condition = " on 32-bit targets",
1441    }
1442    midpoint_impl! { usize, u64, unsigned }
1443    carrying_carryless_mul_impl! { usize, u64 }
1444}
1445
1446#[doc(auto_cfg = false)]
1447#[cfg(target_pointer_width = "64")]
1448impl usize {
1449    uint_impl! {
1450        Self = usize,
1451        ActualT = u64,
1452        SignedT = isize,
1453        BITS = 64,
1454        BITS_MINUS_ONE = 63,
1455        MAX = 18446744073709551615,
1456        rot = 12,
1457        rot_op = "0xaa00000000006e1",
1458        rot_result = "0x6e10aa",
1459        fsh_op = "0x2fe78e45983acd98",
1460        fshl_result = "0x6e12fe",
1461        fshr_result = "0x6e12fe78e45983ac",
1462        clmul_lhs = "0x7890123456789012",
1463        clmul_rhs = "0xdd358416f52ecd34",
1464        clmul_result = "0xa6299579b980928",
1465        swap_op = "0x1234567890123456",
1466        swapped = "0x5634129078563412",
1467        reversed = "0x6a2c48091e6a2c48",
1468        le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1469        be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
1470        to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1471        from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1472        bound_condition = " on 64-bit targets",
1473    }
1474    midpoint_impl! { usize, u128, unsigned }
1475    carrying_carryless_mul_impl! { usize, u128 }
1476}
1477
1478impl usize {
1479    /// Returns an `usize` where every byte is equal to `x`.
1480    #[inline]
1481    pub(crate) const fn repeat_u8(x: u8) -> usize {
1482        usize::from_ne_bytes([x; size_of::<usize>()])
1483    }
1484
1485    /// Returns an `usize` where every byte pair is equal to `x`.
1486    #[inline]
1487    pub(crate) const fn repeat_u16(x: u16) -> usize {
1488        let mut r = 0usize;
1489        let mut i = 0;
1490        while i < size_of::<usize>() {
1491            // Use `wrapping_shl` to make it work on targets with 16-bit `usize`
1492            r = r.wrapping_shl(16) | (x as usize);
1493            i += 2;
1494        }
1495        r
1496    }
1497}
1498
1499/// A classification of floating point numbers.
1500///
1501/// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
1502/// their documentation for more.
1503///
1504/// # Examples
1505///
1506/// ```
1507/// use std::num::FpCategory;
1508///
1509/// let num = 12.4_f32;
1510/// let inf = f32::INFINITY;
1511/// let zero = 0f32;
1512/// let sub: f32 = 1.1754942e-38;
1513/// let nan = f32::NAN;
1514///
1515/// assert_eq!(num.classify(), FpCategory::Normal);
1516/// assert_eq!(inf.classify(), FpCategory::Infinite);
1517/// assert_eq!(zero.classify(), FpCategory::Zero);
1518/// assert_eq!(sub.classify(), FpCategory::Subnormal);
1519/// assert_eq!(nan.classify(), FpCategory::Nan);
1520/// ```
1521#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1522#[stable(feature = "rust1", since = "1.0.0")]
1523pub enum FpCategory {
1524    /// NaN (not a number): this value results from calculations like `(-1.0).sqrt()`.
1525    ///
1526    /// See [the documentation for `f32`](f32) for more information on the unusual properties
1527    /// of NaN.
1528    #[stable(feature = "rust1", since = "1.0.0")]
1529    Nan,
1530
1531    /// Positive or negative infinity, which often results from dividing a nonzero number
1532    /// by zero.
1533    #[stable(feature = "rust1", since = "1.0.0")]
1534    Infinite,
1535
1536    /// Positive or negative zero.
1537    ///
1538    /// See [the documentation for `f32`](f32) for more information on the signedness of zeroes.
1539    #[stable(feature = "rust1", since = "1.0.0")]
1540    Zero,
1541
1542    /// “Subnormal” or “denormal” floating point representation (less precise, relative to
1543    /// their magnitude, than [`Normal`]).
1544    ///
1545    /// Subnormal numbers are larger in magnitude than [`Zero`] but smaller in magnitude than all
1546    /// [`Normal`] numbers.
1547    ///
1548    /// [`Normal`]: Self::Normal
1549    /// [`Zero`]: Self::Zero
1550    #[stable(feature = "rust1", since = "1.0.0")]
1551    Subnormal,
1552
1553    /// A regular floating point number, not any of the exceptional categories.
1554    ///
1555    /// The smallest positive normal numbers are [`f32::MIN_POSITIVE`] and [`f64::MIN_POSITIVE`],
1556    /// and the largest positive normal numbers are [`f32::MAX`] and [`f64::MAX`]. (Unlike signed
1557    /// integers, floating point numbers are symmetric in their range, so negating any of these
1558    /// constants will produce their negative counterpart.)
1559    #[stable(feature = "rust1", since = "1.0.0")]
1560    Normal,
1561}
1562
1563/// Determines if a string of text of that length of that radix could be guaranteed to be
1564/// stored in the given type T.
1565/// Note that if the radix is known to the compiler, it is just the check of digits.len that
1566/// is done at runtime.
1567#[doc(hidden)]
1568#[inline(always)]
1569#[unstable(issue = "none", feature = "std_internals")]
1570pub const fn can_not_overflow<T>(radix: u32, is_signed_ty: bool, digits: &[u8]) -> bool {
1571    radix <= 16 && digits.len() <= size_of::<T>() * 2 - is_signed_ty as usize
1572}
1573
1574#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
1575#[cfg_attr(panic = "immediate-abort", inline)]
1576#[cold]
1577#[track_caller]
1578const fn from_ascii_radix_panic(radix: u32) -> ! {
1579    const_panic!(
1580        "from_ascii_radix: radix must lie in the range `[2, 36]`",
1581        "from_ascii_radix: radix must lie in the range `[2, 36]` - found {radix}",
1582        radix: u32 = radix,
1583    )
1584}
1585
1586macro_rules! from_str_int_impl {
1587    ($signedness:ident $($int_ty:ty)+) => {$(
1588        #[stable(feature = "rust1", since = "1.0.0")]
1589        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1590        impl const FromStr for $int_ty {
1591            type Err = ParseIntError;
1592
1593            /// Parses an integer from a string slice with decimal digits.
1594            ///
1595            /// The characters are expected to be an optional
1596            #[doc = sign_dependent_expr!{
1597                $signedness ?
1598                if signed {
1599                    " `+` or `-` "
1600                }
1601                if unsigned {
1602                    " `+` "
1603                }
1604            }]
1605            /// sign followed by only digits. Leading and trailing non-digit characters (including
1606            /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1607            /// also represent an error.
1608            ///
1609            /// # See also
1610            /// For parsing numbers in other bases, such as binary or hexadecimal,
1611            /// see [`from_str_radix`][Self::from_str_radix].
1612            ///
1613            /// # Examples
1614            ///
1615            /// ```
1616            /// use std::str::FromStr;
1617            ///
1618            #[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_str(\"+10\"), Ok(10));")]
1619            /// ```
1620            /// Trailing space returns error:
1621            /// ```
1622            /// # use std::str::FromStr;
1623            /// #
1624            #[doc = concat!("assert!(", stringify!($int_ty), "::from_str(\"1 \").is_err());")]
1625            /// ```
1626            #[inline]
1627            fn from_str(src: &str) -> Result<$int_ty, ParseIntError> {
1628                <$int_ty>::from_str_radix(src, 10)
1629            }
1630        }
1631
1632        impl $int_ty {
1633            /// Parses an integer from a string slice with digits in a given base.
1634            ///
1635            /// The string is expected to be an optional
1636            #[doc = sign_dependent_expr!{
1637                $signedness ?
1638                if signed {
1639                    " `+` or `-` "
1640                }
1641                if unsigned {
1642                    " `+` "
1643                }
1644            }]
1645            /// sign followed by only digits. Leading and trailing non-digit characters (including
1646            /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1647            /// also represent an error.
1648            ///
1649            /// Digits are a subset of these characters, depending on `radix`:
1650            /// * `0-9`
1651            /// * `a-z`
1652            /// * `A-Z`
1653            ///
1654            /// # Panics
1655            ///
1656            /// This function panics if `radix` is not in the range from 2 to 36.
1657            ///
1658            /// # See also
1659            /// If the string to be parsed is in base 10 (decimal),
1660            /// [`from_str`] or [`str::parse`] can also be used.
1661            ///
1662            // FIXME(#122566): These HTML links work around a rustdoc-json test failure.
1663            /// [`from_str`]: #method.from_str
1664            /// [`str::parse`]: primitive.str.html#method.parse
1665            ///
1666            /// # Examples
1667            ///
1668            /// ```
1669            #[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_str_radix(\"A\", 16), Ok(10));")]
1670            /// ```
1671            /// Trailing space returns error:
1672            /// ```
1673            #[doc = concat!("assert!(", stringify!($int_ty), "::from_str_radix(\"1 \", 10).is_err());")]
1674            /// ```
1675            #[stable(feature = "rust1", since = "1.0.0")]
1676            #[rustc_const_stable(feature = "const_int_from_str", since = "1.82.0")]
1677            #[inline]
1678            pub const fn from_str_radix(src: &str, radix: u32) -> Result<$int_ty, ParseIntError> {
1679                <$int_ty>::from_ascii_radix(src.as_bytes(), radix)
1680            }
1681
1682            /// Parses an integer from an ASCII-byte slice with decimal digits.
1683            ///
1684            /// The characters are expected to be an optional
1685            #[doc = sign_dependent_expr!{
1686                $signedness ?
1687                if signed {
1688                    " `+` or `-` "
1689                }
1690                if unsigned {
1691                    " `+` "
1692                }
1693            }]
1694            /// sign followed by only digits. Leading and trailing non-digit characters (including
1695            /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1696            /// also represent an error.
1697            ///
1698            /// # Examples
1699            ///
1700            /// ```
1701            /// #![feature(int_from_ascii)]
1702            ///
1703            #[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_ascii(b\"+10\"), Ok(10));")]
1704            /// ```
1705            /// Trailing space returns error:
1706            /// ```
1707            /// # #![feature(int_from_ascii)]
1708            /// #
1709            #[doc = concat!("assert!(", stringify!($int_ty), "::from_ascii(b\"1 \").is_err());")]
1710            /// ```
1711            #[unstable(feature = "int_from_ascii", issue = "134821")]
1712            #[inline]
1713            pub const fn from_ascii(src: &[u8]) -> Result<$int_ty, ParseIntError> {
1714                <$int_ty>::from_ascii_radix(src, 10)
1715            }
1716
1717            /// Parses an integer from an ASCII-byte slice with digits in a given base.
1718            ///
1719            /// The characters are expected to be an optional
1720            #[doc = sign_dependent_expr!{
1721                $signedness ?
1722                if signed {
1723                    " `+` or `-` "
1724                }
1725                if unsigned {
1726                    " `+` "
1727                }
1728            }]
1729            /// sign followed by only digits. Leading and trailing non-digit characters (including
1730            /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1731            /// also represent an error.
1732            ///
1733            /// Digits are a subset of these characters, depending on `radix`:
1734            /// * `0-9`
1735            /// * `a-z`
1736            /// * `A-Z`
1737            ///
1738            /// # Panics
1739            ///
1740            /// This function panics if `radix` is not in the range from 2 to 36.
1741            ///
1742            /// # Examples
1743            ///
1744            /// ```
1745            /// #![feature(int_from_ascii)]
1746            ///
1747            #[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_ascii_radix(b\"A\", 16), Ok(10));")]
1748            /// ```
1749            /// Trailing space returns error:
1750            /// ```
1751            /// # #![feature(int_from_ascii)]
1752            /// #
1753            #[doc = concat!("assert!(", stringify!($int_ty), "::from_ascii_radix(b\"1 \", 10).is_err());")]
1754            /// ```
1755            #[unstable(feature = "int_from_ascii", issue = "134821")]
1756            #[inline]
1757            pub const fn from_ascii_radix(src: &[u8], radix: u32) -> Result<$int_ty, ParseIntError> {
1758                use self::IntErrorKind::*;
1759                use self::ParseIntError as PIE;
1760
1761                if 2 > radix || radix > 36 {
1762                    from_ascii_radix_panic(radix);
1763                }
1764
1765                if src.is_empty() {
1766                    return Err(PIE { kind: Empty });
1767                }
1768
1769                #[allow(unused_comparisons)]
1770                let is_signed_ty = 0 > <$int_ty>::MIN;
1771
1772                let (is_positive, mut digits) = match src {
1773                    [b'+' | b'-'] => {
1774                        return Err(PIE { kind: InvalidDigit });
1775                    }
1776                    [b'+', rest @ ..] => (true, rest),
1777                    [b'-', rest @ ..] if is_signed_ty => (false, rest),
1778                    _ => (true, src),
1779                };
1780
1781                let mut result = 0;
1782
1783                macro_rules! unwrap_or_PIE {
1784                    ($option:expr, $kind:ident) => {
1785                        match $option {
1786                            Some(value) => value,
1787                            None => return Err(PIE { kind: $kind }),
1788                        }
1789                    };
1790                }
1791
1792                if can_not_overflow::<$int_ty>(radix, is_signed_ty, digits) {
1793                    // If the len of the str is short compared to the range of the type
1794                    // we are parsing into, then we can be certain that an overflow will not occur.
1795                    // This bound is when `radix.pow(digits.len()) - 1 <= T::MAX` but the condition
1796                    // above is a faster (conservative) approximation of this.
1797                    //
1798                    // Consider radix 16 as it has the highest information density per digit and will thus overflow the earliest:
1799                    // `u8::MAX` is `ff` - any str of len 2 is guaranteed to not overflow.
1800                    // `i8::MAX` is `7f` - only a str of len 1 is guaranteed to not overflow.
1801                    macro_rules! run_unchecked_loop {
1802                        ($unchecked_additive_op:tt) => {{
1803                            while let [c, rest @ ..] = digits {
1804                                result = result * (radix as $int_ty);
1805                                let x = unwrap_or_PIE!((*c as char).to_digit(radix), InvalidDigit);
1806                                result = result $unchecked_additive_op (x as $int_ty);
1807                                digits = rest;
1808                            }
1809                        }};
1810                    }
1811                    if is_positive {
1812                        run_unchecked_loop!(+)
1813                    } else {
1814                        run_unchecked_loop!(-)
1815                    };
1816                } else {
1817                    macro_rules! run_checked_loop {
1818                        ($checked_additive_op:ident, $overflow_err:ident) => {{
1819                            while let [c, rest @ ..] = digits {
1820                                // When `radix` is passed in as a literal, rather than doing a slow `imul`
1821                                // the compiler can use shifts if `radix` can be expressed as a
1822                                // sum of powers of 2 (x*10 can be written as x*8 + x*2).
1823                                // When the compiler can't use these optimisations,
1824                                // the latency of the multiplication can be hidden by issuing it
1825                                // before the result is needed to improve performance on
1826                                // modern out-of-order CPU as multiplication here is slower
1827                                // than the other instructions, we can get the end result faster
1828                                // doing multiplication first and let the CPU spends other cycles
1829                                // doing other computation and get multiplication result later.
1830                                let mul = result.checked_mul(radix as $int_ty);
1831                                let x = unwrap_or_PIE!((*c as char).to_digit(radix), InvalidDigit) as $int_ty;
1832                                result = unwrap_or_PIE!(mul, $overflow_err);
1833                                result = unwrap_or_PIE!(<$int_ty>::$checked_additive_op(result, x), $overflow_err);
1834                                digits = rest;
1835                            }
1836                        }};
1837                    }
1838                    if is_positive {
1839                        run_checked_loop!(checked_add, PosOverflow)
1840                    } else {
1841                        run_checked_loop!(checked_sub, NegOverflow)
1842                    };
1843                }
1844                Ok(result)
1845            }
1846        }
1847    )*}
1848}
1849
1850from_str_int_impl! { signed isize i8 i16 i32 i64 i128 }
1851from_str_int_impl! { unsigned usize u8 u16 u32 u64 u128 }