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