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