1 //! Numeric traits and functions for the built-in numeric types.
3 #![stable(feature = "rust1", since = "1.0.0")]
8 use crate::ops::{Add, Mul, Sub};
9 use crate::str::FromStr;
11 // Used because the `?` operator is not allowed in a const context.
12 macro_rules! try_opt {
21 #[allow_internal_unstable(const_likely)]
22 macro_rules! unlikely {
24 intrinsics::unlikely($e)
28 // All these modules are technically private and only exposed for coretests:
29 #[cfg(not(no_fp_fmt_parse))]
31 #[cfg(not(no_fp_fmt_parse))]
33 #[cfg(not(no_fp_fmt_parse))]
35 #[cfg(not(no_fp_fmt_parse))]
40 mod int_macros; // import int_impl!
42 mod uint_macros; // import uint_impl!
47 #[unstable(feature = "saturating_int_impl", issue = "87920")]
51 #[unstable(feature = "saturating_int_impl", issue = "87920")]
52 pub use saturating::Saturating;
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub use wrapping::Wrapping;
56 #[stable(feature = "rust1", since = "1.0.0")]
57 #[cfg(not(no_fp_fmt_parse))]
58 pub use dec2flt::ParseFloatError;
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub use error::ParseIntError;
63 #[stable(feature = "nonzero", since = "1.28.0")]
64 pub use nonzero::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize};
66 #[stable(feature = "signed_nonzero", since = "1.34.0")]
67 pub use nonzero::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize};
69 #[stable(feature = "try_from", since = "1.34.0")]
70 pub use error::TryFromIntError;
72 #[stable(feature = "int_error_matching", since = "1.55.0")]
73 pub use error::IntErrorKind;
75 macro_rules! usize_isize_to_xe_bytes_doc {
79 **Note**: This function returns an array of length 2, 4 or 8 bytes
80 depending on the target pointer size.
86 macro_rules! usize_isize_from_xe_bytes_doc {
90 **Note**: This function takes an array of length 2, 4 or 8 bytes
91 depending on the target pointer size.
97 macro_rules! widening_impl {
98 ($SelfT:ty, $WideT:ty, $BITS:literal, unsigned) => {
99 /// Calculates the complete product `self * rhs` without the possibility to overflow.
101 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
102 /// of the result as two separate values, in that order.
108 /// Please note that this example is shared between integer types.
109 /// Which explains why `u32` is used here.
112 /// #![feature(bigint_helper_methods)]
113 /// assert_eq!(5u32.widening_mul(2), (10, 0));
114 /// assert_eq!(1_000_000_000u32.widening_mul(10), (1410065408, 2));
116 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
117 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
118 #[must_use = "this returns the result of the operation, \
119 without modifying the original"]
121 pub const fn widening_mul(self, rhs: Self) -> (Self, Self) {
122 // note: longer-term this should be done via an intrinsic,
123 // but for now we can deal without an impl for u128/i128
124 // SAFETY: overflow will be contained within the wider types
125 let wide = unsafe { (self as $WideT).unchecked_mul(rhs as $WideT) };
126 (wide as $SelfT, (wide >> $BITS) as $SelfT)
129 /// Calculates the "full multiplication" `self * rhs + carry`
130 /// without the possibility to overflow.
132 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
133 /// of the result as two separate values, in that order.
135 /// Performs "long multiplication" which takes in an extra amount to add, and may return an
136 /// additional amount of overflow. This allows for chaining together multiple
137 /// multiplications to create "big integers" which represent larger values.
143 /// Please note that this example is shared between integer types.
144 /// Which explains why `u32` is used here.
147 /// #![feature(bigint_helper_methods)]
148 /// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
149 /// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
150 /// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
151 /// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
152 #[doc = concat!("assert_eq!(",
153 stringify!($SelfT), "::MAX.carrying_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
154 "(0, ", stringify!($SelfT), "::MAX));"
158 /// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
159 /// except that it gives the value of the overflow instead of just whether one happened:
162 /// #![feature(bigint_helper_methods)]
163 /// let r = u8::carrying_mul(7, 13, 0);
164 /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
165 /// let r = u8::carrying_mul(13, 42, 0);
166 /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
169 /// The value of the first field in the returned tuple matches what you'd get
170 /// by combining the [`wrapping_mul`](Self::wrapping_mul) and
171 /// [`wrapping_add`](Self::wrapping_add) methods:
174 /// #![feature(bigint_helper_methods)]
176 /// 789_u16.carrying_mul(456, 123).0,
177 /// 789_u16.wrapping_mul(456).wrapping_add(123),
180 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
181 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
182 #[must_use = "this returns the result of the operation, \
183 without modifying the original"]
185 pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
186 // note: longer-term this should be done via an intrinsic,
187 // but for now we can deal without an impl for u128/i128
188 // SAFETY: overflow will be contained within the wider types
190 (self as $WideT).unchecked_mul(rhs as $WideT).unchecked_add(carry as $WideT)
192 (wide as $SelfT, (wide >> $BITS) as $SelfT)
198 int_impl! { i8, i8, u8, 8, 7, -128, 127, 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
199 "[0x12]", "[0x12]", "", "" }
203 int_impl! { i16, i16, u16, 16, 15, -32768, 32767, 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
204 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
208 int_impl! { i32, i32, u32, 32, 31, -2147483648, 2147483647, 8, "0x10000b3", "0xb301",
209 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
210 "[0x12, 0x34, 0x56, 0x78]", "", "" }
214 int_impl! { i64, i64, u64, 64, 63, -9223372036854775808, 9223372036854775807, 12,
215 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
216 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
217 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
221 int_impl! { i128, i128, u128, 128, 127, -170141183460469231731687303715884105728,
222 170141183460469231731687303715884105727, 16,
223 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
224 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
225 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
226 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
227 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
228 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
231 #[cfg(target_pointer_width = "16")]
233 int_impl! { isize, i16, usize, 16, 15, -32768, 32767, 4, "-0x5ffd", "0x3a", "0x1234",
234 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
235 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
238 #[cfg(target_pointer_width = "32")]
240 int_impl! { isize, i32, usize, 32, 31, -2147483648, 2147483647, 8, "0x10000b3", "0xb301",
241 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
242 "[0x12, 0x34, 0x56, 0x78]",
243 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
246 #[cfg(target_pointer_width = "64")]
248 int_impl! { isize, i64, usize, 64, 63, -9223372036854775808, 9223372036854775807,
249 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
250 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
251 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
252 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
255 /// If 6th bit set ascii is upper case.
256 const ASCII_CASE_MASK: u8 = 0b0010_0000;
259 uint_impl! { u8, u8, i8, NonZeroU8, 8, 255, 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
261 widening_impl! { u8, u16, 8, unsigned }
263 /// Checks if the value is within the ASCII range.
268 /// let ascii = 97u8;
269 /// let non_ascii = 150u8;
271 /// assert!(ascii.is_ascii());
272 /// assert!(!non_ascii.is_ascii());
275 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
276 #[rustc_const_stable(feature = "const_u8_is_ascii", since = "1.43.0")]
278 pub const fn is_ascii(&self) -> bool {
282 /// Makes a copy of the value in its ASCII upper case equivalent.
284 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
285 /// but non-ASCII letters are unchanged.
287 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
292 /// let lowercase_a = 97u8;
294 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
297 /// [`make_ascii_uppercase`]: Self::make_ascii_uppercase
298 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
299 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
300 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
302 pub const fn to_ascii_uppercase(&self) -> u8 {
303 // Toggle the fifth bit if this is a lowercase letter
304 *self ^ ((self.is_ascii_lowercase() as u8) * ASCII_CASE_MASK)
307 /// Makes a copy of the value in its ASCII lower case equivalent.
309 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
310 /// but non-ASCII letters are unchanged.
312 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
317 /// let uppercase_a = 65u8;
319 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
322 /// [`make_ascii_lowercase`]: Self::make_ascii_lowercase
323 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
324 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
325 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
327 pub const fn to_ascii_lowercase(&self) -> u8 {
328 // Set the fifth bit if this is an uppercase letter
329 *self | (self.is_ascii_uppercase() as u8 * ASCII_CASE_MASK)
332 /// Assumes self is ascii
334 pub(crate) const fn ascii_change_case_unchecked(&self) -> u8 {
335 *self ^ ASCII_CASE_MASK
338 /// Checks that two values are an ASCII case-insensitive match.
340 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
345 /// let lowercase_a = 97u8;
346 /// let uppercase_a = 65u8;
348 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
350 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
351 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
353 pub const fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
354 self.to_ascii_lowercase() == other.to_ascii_lowercase()
357 /// Converts this value to its ASCII upper case equivalent in-place.
359 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
360 /// but non-ASCII letters are unchanged.
362 /// To return a new uppercased value without modifying the existing one, use
363 /// [`to_ascii_uppercase`].
368 /// let mut byte = b'a';
370 /// byte.make_ascii_uppercase();
372 /// assert_eq!(b'A', byte);
375 /// [`to_ascii_uppercase`]: Self::to_ascii_uppercase
376 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
378 pub fn make_ascii_uppercase(&mut self) {
379 *self = self.to_ascii_uppercase();
382 /// Converts this value to its ASCII lower case equivalent in-place.
384 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
385 /// but non-ASCII letters are unchanged.
387 /// To return a new lowercased value without modifying the existing one, use
388 /// [`to_ascii_lowercase`].
393 /// let mut byte = b'A';
395 /// byte.make_ascii_lowercase();
397 /// assert_eq!(b'a', byte);
400 /// [`to_ascii_lowercase`]: Self::to_ascii_lowercase
401 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
403 pub fn make_ascii_lowercase(&mut self) {
404 *self = self.to_ascii_lowercase();
407 /// Checks if the value is an ASCII alphabetic character:
409 /// - U+0041 'A' ..= U+005A 'Z', or
410 /// - U+0061 'a' ..= U+007A 'z'.
415 /// let uppercase_a = b'A';
416 /// let uppercase_g = b'G';
420 /// let percent = b'%';
421 /// let space = b' ';
423 /// let esc = b'\x1b';
425 /// assert!(uppercase_a.is_ascii_alphabetic());
426 /// assert!(uppercase_g.is_ascii_alphabetic());
427 /// assert!(a.is_ascii_alphabetic());
428 /// assert!(g.is_ascii_alphabetic());
429 /// assert!(!zero.is_ascii_alphabetic());
430 /// assert!(!percent.is_ascii_alphabetic());
431 /// assert!(!space.is_ascii_alphabetic());
432 /// assert!(!lf.is_ascii_alphabetic());
433 /// assert!(!esc.is_ascii_alphabetic());
436 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
437 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
439 pub const fn is_ascii_alphabetic(&self) -> bool {
440 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
443 /// Checks if the value is an ASCII uppercase character:
444 /// U+0041 'A' ..= U+005A 'Z'.
449 /// let uppercase_a = b'A';
450 /// let uppercase_g = b'G';
454 /// let percent = b'%';
455 /// let space = b' ';
457 /// let esc = b'\x1b';
459 /// assert!(uppercase_a.is_ascii_uppercase());
460 /// assert!(uppercase_g.is_ascii_uppercase());
461 /// assert!(!a.is_ascii_uppercase());
462 /// assert!(!g.is_ascii_uppercase());
463 /// assert!(!zero.is_ascii_uppercase());
464 /// assert!(!percent.is_ascii_uppercase());
465 /// assert!(!space.is_ascii_uppercase());
466 /// assert!(!lf.is_ascii_uppercase());
467 /// assert!(!esc.is_ascii_uppercase());
470 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
471 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
473 pub const fn is_ascii_uppercase(&self) -> bool {
474 matches!(*self, b'A'..=b'Z')
477 /// Checks if the value is an ASCII lowercase character:
478 /// U+0061 'a' ..= U+007A 'z'.
483 /// let uppercase_a = b'A';
484 /// let uppercase_g = b'G';
488 /// let percent = b'%';
489 /// let space = b' ';
491 /// let esc = b'\x1b';
493 /// assert!(!uppercase_a.is_ascii_lowercase());
494 /// assert!(!uppercase_g.is_ascii_lowercase());
495 /// assert!(a.is_ascii_lowercase());
496 /// assert!(g.is_ascii_lowercase());
497 /// assert!(!zero.is_ascii_lowercase());
498 /// assert!(!percent.is_ascii_lowercase());
499 /// assert!(!space.is_ascii_lowercase());
500 /// assert!(!lf.is_ascii_lowercase());
501 /// assert!(!esc.is_ascii_lowercase());
504 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
505 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
507 pub const fn is_ascii_lowercase(&self) -> bool {
508 matches!(*self, b'a'..=b'z')
511 /// Checks if the value is an ASCII alphanumeric character:
513 /// - U+0041 'A' ..= U+005A 'Z', or
514 /// - U+0061 'a' ..= U+007A 'z', or
515 /// - U+0030 '0' ..= U+0039 '9'.
520 /// let uppercase_a = b'A';
521 /// let uppercase_g = b'G';
525 /// let percent = b'%';
526 /// let space = b' ';
528 /// let esc = b'\x1b';
530 /// assert!(uppercase_a.is_ascii_alphanumeric());
531 /// assert!(uppercase_g.is_ascii_alphanumeric());
532 /// assert!(a.is_ascii_alphanumeric());
533 /// assert!(g.is_ascii_alphanumeric());
534 /// assert!(zero.is_ascii_alphanumeric());
535 /// assert!(!percent.is_ascii_alphanumeric());
536 /// assert!(!space.is_ascii_alphanumeric());
537 /// assert!(!lf.is_ascii_alphanumeric());
538 /// assert!(!esc.is_ascii_alphanumeric());
541 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
542 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
544 pub const fn is_ascii_alphanumeric(&self) -> bool {
545 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
548 /// Checks if the value is an ASCII decimal digit:
549 /// U+0030 '0' ..= U+0039 '9'.
554 /// let uppercase_a = b'A';
555 /// let uppercase_g = b'G';
559 /// let percent = b'%';
560 /// let space = b' ';
562 /// let esc = b'\x1b';
564 /// assert!(!uppercase_a.is_ascii_digit());
565 /// assert!(!uppercase_g.is_ascii_digit());
566 /// assert!(!a.is_ascii_digit());
567 /// assert!(!g.is_ascii_digit());
568 /// assert!(zero.is_ascii_digit());
569 /// assert!(!percent.is_ascii_digit());
570 /// assert!(!space.is_ascii_digit());
571 /// assert!(!lf.is_ascii_digit());
572 /// assert!(!esc.is_ascii_digit());
575 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
576 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
578 pub const fn is_ascii_digit(&self) -> bool {
579 matches!(*self, b'0'..=b'9')
582 /// Checks if the value is an ASCII hexadecimal digit:
584 /// - U+0030 '0' ..= U+0039 '9', or
585 /// - U+0041 'A' ..= U+0046 'F', or
586 /// - U+0061 'a' ..= U+0066 'f'.
591 /// let uppercase_a = b'A';
592 /// let uppercase_g = b'G';
596 /// let percent = b'%';
597 /// let space = b' ';
599 /// let esc = b'\x1b';
601 /// assert!(uppercase_a.is_ascii_hexdigit());
602 /// assert!(!uppercase_g.is_ascii_hexdigit());
603 /// assert!(a.is_ascii_hexdigit());
604 /// assert!(!g.is_ascii_hexdigit());
605 /// assert!(zero.is_ascii_hexdigit());
606 /// assert!(!percent.is_ascii_hexdigit());
607 /// assert!(!space.is_ascii_hexdigit());
608 /// assert!(!lf.is_ascii_hexdigit());
609 /// assert!(!esc.is_ascii_hexdigit());
612 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
613 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
615 pub const fn is_ascii_hexdigit(&self) -> bool {
616 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
619 /// Checks if the value is an ASCII punctuation character:
621 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
622 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
623 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
624 /// - U+007B ..= U+007E `{ | } ~`
629 /// let uppercase_a = b'A';
630 /// let uppercase_g = b'G';
634 /// let percent = b'%';
635 /// let space = b' ';
637 /// let esc = b'\x1b';
639 /// assert!(!uppercase_a.is_ascii_punctuation());
640 /// assert!(!uppercase_g.is_ascii_punctuation());
641 /// assert!(!a.is_ascii_punctuation());
642 /// assert!(!g.is_ascii_punctuation());
643 /// assert!(!zero.is_ascii_punctuation());
644 /// assert!(percent.is_ascii_punctuation());
645 /// assert!(!space.is_ascii_punctuation());
646 /// assert!(!lf.is_ascii_punctuation());
647 /// assert!(!esc.is_ascii_punctuation());
650 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
651 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
653 pub const fn is_ascii_punctuation(&self) -> bool {
654 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
657 /// Checks if the value is an ASCII graphic character:
658 /// U+0021 '!' ..= U+007E '~'.
663 /// let uppercase_a = b'A';
664 /// let uppercase_g = b'G';
668 /// let percent = b'%';
669 /// let space = b' ';
671 /// let esc = b'\x1b';
673 /// assert!(uppercase_a.is_ascii_graphic());
674 /// assert!(uppercase_g.is_ascii_graphic());
675 /// assert!(a.is_ascii_graphic());
676 /// assert!(g.is_ascii_graphic());
677 /// assert!(zero.is_ascii_graphic());
678 /// assert!(percent.is_ascii_graphic());
679 /// assert!(!space.is_ascii_graphic());
680 /// assert!(!lf.is_ascii_graphic());
681 /// assert!(!esc.is_ascii_graphic());
684 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
685 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
687 pub const fn is_ascii_graphic(&self) -> bool {
688 matches!(*self, b'!'..=b'~')
691 /// Checks if the value is an ASCII whitespace character:
692 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
693 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
695 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
696 /// whitespace][infra-aw]. There are several other definitions in
697 /// wide use. For instance, [the POSIX locale][pct] includes
698 /// U+000B VERTICAL TAB as well as all the above characters,
699 /// but—from the very same specification—[the default rule for
700 /// "field splitting" in the Bourne shell][bfs] considers *only*
701 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
703 /// If you are writing a program that will process an existing
704 /// file format, check what that format's definition of whitespace is
705 /// before using this function.
707 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
708 /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
709 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
714 /// let uppercase_a = b'A';
715 /// let uppercase_g = b'G';
719 /// let percent = b'%';
720 /// let space = b' ';
722 /// let esc = b'\x1b';
724 /// assert!(!uppercase_a.is_ascii_whitespace());
725 /// assert!(!uppercase_g.is_ascii_whitespace());
726 /// assert!(!a.is_ascii_whitespace());
727 /// assert!(!g.is_ascii_whitespace());
728 /// assert!(!zero.is_ascii_whitespace());
729 /// assert!(!percent.is_ascii_whitespace());
730 /// assert!(space.is_ascii_whitespace());
731 /// assert!(lf.is_ascii_whitespace());
732 /// assert!(!esc.is_ascii_whitespace());
735 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
736 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
738 pub const fn is_ascii_whitespace(&self) -> bool {
739 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
742 /// Checks if the value is an ASCII control character:
743 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
744 /// Note that most ASCII whitespace characters are control
745 /// characters, but SPACE is not.
750 /// let uppercase_a = b'A';
751 /// let uppercase_g = b'G';
755 /// let percent = b'%';
756 /// let space = b' ';
758 /// let esc = b'\x1b';
760 /// assert!(!uppercase_a.is_ascii_control());
761 /// assert!(!uppercase_g.is_ascii_control());
762 /// assert!(!a.is_ascii_control());
763 /// assert!(!g.is_ascii_control());
764 /// assert!(!zero.is_ascii_control());
765 /// assert!(!percent.is_ascii_control());
766 /// assert!(!space.is_ascii_control());
767 /// assert!(lf.is_ascii_control());
768 /// assert!(esc.is_ascii_control());
771 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
772 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
774 pub const fn is_ascii_control(&self) -> bool {
775 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
778 /// Returns an iterator that produces an escaped version of a `u8`,
779 /// treating it as an ASCII character.
781 /// The behavior is identical to [`ascii::escape_default`].
787 /// assert_eq!("0", b'0'.escape_ascii().to_string());
788 /// assert_eq!("\\t", b'\t'.escape_ascii().to_string());
789 /// assert_eq!("\\r", b'\r'.escape_ascii().to_string());
790 /// assert_eq!("\\n", b'\n'.escape_ascii().to_string());
791 /// assert_eq!("\\'", b'\''.escape_ascii().to_string());
792 /// assert_eq!("\\\"", b'"'.escape_ascii().to_string());
793 /// assert_eq!("\\\\", b'\\'.escape_ascii().to_string());
794 /// assert_eq!("\\x9d", b'\x9d'.escape_ascii().to_string());
796 #[must_use = "this returns the escaped byte as an iterator, \
797 without modifying the original"]
798 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
800 pub fn escape_ascii(self) -> ascii::EscapeDefault {
801 ascii::escape_default(self)
805 pub(crate) const fn is_utf8_char_boundary(self) -> bool {
806 // This is bit magic equivalent to: b < 128 || b >= 192
807 (self as i8) >= -0x40
812 uint_impl! { u16, u16, i16, NonZeroU16, 16, 65535, 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
813 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
814 widening_impl! { u16, u32, 16, unsigned }
816 /// Checks if the value is a Unicode surrogate code point, which are disallowed values for [`char`].
821 /// #![feature(utf16_extra)]
823 /// let low_non_surrogate = 0xA000u16;
824 /// let low_surrogate = 0xD800u16;
825 /// let high_surrogate = 0xDC00u16;
826 /// let high_non_surrogate = 0xE000u16;
828 /// assert!(!low_non_surrogate.is_utf16_surrogate());
829 /// assert!(low_surrogate.is_utf16_surrogate());
830 /// assert!(high_surrogate.is_utf16_surrogate());
831 /// assert!(!high_non_surrogate.is_utf16_surrogate());
834 #[unstable(feature = "utf16_extra", issue = "94919")]
835 #[rustc_const_unstable(feature = "utf16_extra_const", issue = "94919")]
837 pub const fn is_utf16_surrogate(self) -> bool {
838 matches!(self, 0xD800..=0xDFFF)
843 uint_impl! { u32, u32, i32, NonZeroU32, 32, 4294967295, 8, "0x10000b3", "0xb301", "0x12345678",
844 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
845 widening_impl! { u32, u64, 32, unsigned }
849 uint_impl! { u64, u64, i64, NonZeroU64, 64, 18446744073709551615, 12, "0xaa00000000006e1", "0x6e10aa",
850 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
851 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
852 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
854 widening_impl! { u64, u128, 64, unsigned }
858 uint_impl! { u128, u128, i128, NonZeroU128, 128, 340282366920938463463374607431768211455, 16,
859 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
860 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
861 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
862 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
863 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
864 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
868 #[cfg(target_pointer_width = "16")]
870 uint_impl! { usize, u16, isize, NonZeroUsize, 16, 65535, 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
871 "[0x34, 0x12]", "[0x12, 0x34]",
872 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
873 widening_impl! { usize, u32, 16, unsigned }
875 #[cfg(target_pointer_width = "32")]
877 uint_impl! { usize, u32, isize, NonZeroUsize, 32, 4294967295, 8, "0x10000b3", "0xb301", "0x12345678",
878 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
879 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
880 widening_impl! { usize, u64, 32, unsigned }
883 #[cfg(target_pointer_width = "64")]
885 uint_impl! { usize, u64, isize, NonZeroUsize, 64, 18446744073709551615, 12, "0xaa00000000006e1", "0x6e10aa",
886 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
887 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
888 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
889 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
890 widening_impl! { usize, u128, 64, unsigned }
893 /// A classification of floating point numbers.
895 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
896 /// their documentation for more.
901 /// use std::num::FpCategory;
903 /// let num = 12.4_f32;
904 /// let inf = f32::INFINITY;
906 /// let sub: f32 = 1.1754942e-38;
907 /// let nan = f32::NAN;
909 /// assert_eq!(num.classify(), FpCategory::Normal);
910 /// assert_eq!(inf.classify(), FpCategory::Infinite);
911 /// assert_eq!(zero.classify(), FpCategory::Zero);
912 /// assert_eq!(nan.classify(), FpCategory::Nan);
913 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
915 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
916 #[stable(feature = "rust1", since = "1.0.0")]
917 pub enum FpCategory {
918 /// NaN (not a number): this value results from calculations like `(-1.0).sqrt()`.
920 /// See [the documentation for `f32`](f32) for more information on the unusual properties
922 #[stable(feature = "rust1", since = "1.0.0")]
925 /// Positive or negative infinity, which often results from dividing a nonzero number
927 #[stable(feature = "rust1", since = "1.0.0")]
930 /// Positive or negative zero.
932 /// See [the documentation for `f32`](f32) for more information on the signedness of zeroes.
933 #[stable(feature = "rust1", since = "1.0.0")]
936 /// “Subnormal” or “denormal” floating point representation (less precise, relative to
937 /// their magnitude, than [`Normal`]).
939 /// Subnormal numbers are larger in magnitude than [`Zero`] but smaller in magnitude than all
940 /// [`Normal`] numbers.
942 /// [`Normal`]: Self::Normal
943 /// [`Zero`]: Self::Zero
944 #[stable(feature = "rust1", since = "1.0.0")]
947 /// A regular floating point number, not any of the exceptional categories.
949 /// The smallest positive normal numbers are [`f32::MIN_POSITIVE`] and [`f64::MIN_POSITIVE`],
950 /// and the largest positive normal numbers are [`f32::MAX`] and [`f64::MAX`]. (Unlike signed
951 /// integers, floating point numbers are symmetric in their range, so negating any of these
952 /// constants will produce their negative counterpart.)
953 #[stable(feature = "rust1", since = "1.0.0")]
958 trait FromStrRadixHelper:
959 PartialOrd + Copy + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self>
962 fn from_u32(u: u32) -> Self;
963 fn checked_mul(&self, other: u32) -> Option<Self>;
964 fn checked_sub(&self, other: u32) -> Option<Self>;
965 fn checked_add(&self, other: u32) -> Option<Self>;
968 macro_rules! from_str_radix_int_impl {
970 #[stable(feature = "rust1", since = "1.0.0")]
971 impl FromStr for $t {
972 type Err = ParseIntError;
973 fn from_str(src: &str) -> Result<Self, ParseIntError> {
974 from_str_radix(src, 10)
979 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
981 macro_rules! impl_helper_for {
982 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
983 const MIN: Self = Self::MIN;
985 fn from_u32(u: u32) -> Self { u as Self }
987 fn checked_mul(&self, other: u32) -> Option<Self> {
988 Self::checked_mul(*self, other as Self)
991 fn checked_sub(&self, other: u32) -> Option<Self> {
992 Self::checked_sub(*self, other as Self)
995 fn checked_add(&self, other: u32) -> Option<Self> {
996 Self::checked_add(*self, other as Self)
1000 impl_helper_for! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
1002 /// Determines if a string of text of that length of that radix could be guaranteed to be
1003 /// stored in the given type T.
1004 /// Note that if the radix is known to the compiler, it is just the check of digits.len that
1005 /// is done at runtime.
1008 #[unstable(issue = "none", feature = "std_internals")]
1009 pub fn can_not_overflow<T>(radix: u32, is_signed_ty: bool, digits: &[u8]) -> bool {
1010 radix <= 16 && digits.len() <= mem::size_of::<T>() * 2 - is_signed_ty as usize
1013 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
1014 use self::IntErrorKind::*;
1015 use self::ParseIntError as PIE;
1018 (2..=36).contains(&radix),
1019 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1024 return Err(PIE { kind: Empty });
1027 let is_signed_ty = T::from_u32(0) > T::MIN;
1029 // all valid digits are ascii, so we will just iterate over the utf8 bytes
1030 // and cast them to chars. .to_digit() will safely return None for anything
1031 // other than a valid ascii digit for the given radix, including the first-byte
1032 // of multi-byte sequences
1033 let src = src.as_bytes();
1035 let (is_positive, digits) = match src[0] {
1036 b'+' | b'-' if src[1..].is_empty() => {
1037 return Err(PIE { kind: InvalidDigit });
1039 b'+' => (true, &src[1..]),
1040 b'-' if is_signed_ty => (false, &src[1..]),
1044 let mut result = T::from_u32(0);
1046 if can_not_overflow::<T>(radix, is_signed_ty, digits) {
1047 // If the len of the str is short compared to the range of the type
1048 // we are parsing into, then we can be certain that an overflow will not occur.
1049 // This bound is when `radix.pow(digits.len()) - 1 <= T::MAX` but the condition
1050 // above is a faster (conservative) approximation of this.
1052 // Consider radix 16 as it has the highest information density per digit and will thus overflow the earliest:
1053 // `u8::MAX` is `ff` - any str of len 2 is guaranteed to not overflow.
1054 // `i8::MAX` is `7f` - only a str of len 1 is guaranteed to not overflow.
1055 macro_rules! run_unchecked_loop {
1056 ($unchecked_additive_op:expr) => {
1058 result = result * T::from_u32(radix);
1059 let x = (c as char).to_digit(radix).ok_or(PIE { kind: InvalidDigit })?;
1060 result = $unchecked_additive_op(result, T::from_u32(x));
1065 run_unchecked_loop!(<T as core::ops::Add>::add)
1067 run_unchecked_loop!(<T as core::ops::Sub>::sub)
1070 macro_rules! run_checked_loop {
1071 ($checked_additive_op:ident, $overflow_err:expr) => {
1073 // When `radix` is passed in as a literal, rather than doing a slow `imul`
1074 // the compiler can use shifts if `radix` can be expressed as a
1075 // sum of powers of 2 (x*10 can be written as x*8 + x*2).
1076 // When the compiler can't use these optimisations,
1077 // the latency of the multiplication can be hidden by issuing it
1078 // before the result is needed to improve performance on
1079 // modern out-of-order CPU as multiplication here is slower
1080 // than the other instructions, we can get the end result faster
1081 // doing multiplication first and let the CPU spends other cycles
1082 // doing other computation and get multiplication result later.
1083 let mul = result.checked_mul(radix);
1084 let x = (c as char).to_digit(radix).ok_or(PIE { kind: InvalidDigit })?;
1085 result = mul.ok_or_else($overflow_err)?;
1086 result = T::$checked_additive_op(&result, x).ok_or_else($overflow_err)?;
1091 run_checked_loop!(checked_add, || PIE { kind: PosOverflow })
1093 run_checked_loop!(checked_sub, || PIE { kind: NegOverflow })