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