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