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