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