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