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