Thanks to visit codestin.com
Credit goes to doc.rust-lang.org

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