1 //! Numeric traits and functions for the built-in numeric types.
3 #![stable(feature = "rust1", since = "1.0.0")]
8 use crate::str::FromStr;
10 // Used because the `?` operator is not allowed in a const context.
11 macro_rules! try_opt {
20 #[allow_internal_unstable(const_likely)]
21 macro_rules! unlikely {
23 intrinsics::unlikely($e)
27 // All these modules are technically private and only exposed for coretests:
28 #[cfg(not(no_fp_fmt_parse))]
30 #[cfg(not(no_fp_fmt_parse))]
32 #[cfg(not(no_fp_fmt_parse))]
34 #[cfg(not(no_fp_fmt_parse))]
39 mod int_macros; // import int_impl!
41 mod uint_macros; // import uint_impl!
46 #[unstable(feature = "saturating_int_impl", issue = "87920")]
50 #[unstable(feature = "saturating_int_impl", issue = "87920")]
51 pub use saturating::Saturating;
52 #[stable(feature = "rust1", since = "1.0.0")]
53 pub use wrapping::Wrapping;
55 #[stable(feature = "rust1", since = "1.0.0")]
56 #[cfg(not(no_fp_fmt_parse))]
57 pub use dec2flt::ParseFloatError;
59 #[stable(feature = "rust1", since = "1.0.0")]
60 pub use error::ParseIntError;
62 #[stable(feature = "nonzero", since = "1.28.0")]
63 pub use nonzero::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize};
65 #[stable(feature = "signed_nonzero", since = "1.34.0")]
66 pub use nonzero::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize};
68 #[stable(feature = "try_from", since = "1.34.0")]
69 pub use error::TryFromIntError;
71 #[stable(feature = "int_error_matching", since = "1.55.0")]
72 pub use error::IntErrorKind;
74 macro_rules! usize_isize_to_xe_bytes_doc {
78 **Note**: This function returns an array of length 2, 4 or 8 bytes
79 depending on the target pointer size.
85 macro_rules! usize_isize_from_xe_bytes_doc {
89 **Note**: This function takes an array of length 2, 4 or 8 bytes
90 depending on the target pointer size.
96 macro_rules! widening_impl {
97 ($SelfT:ty, $WideT:ty, $BITS:literal, unsigned) => {
98 widening_impl!($SelfT, $WideT, $BITS, "");
100 ($SelfT:ty, $WideT:ty, $BITS:literal, signed) => {
101 widening_impl!($SelfT, $WideT, $BITS, "# //");
103 ($SelfT:ty, $WideT:ty, $BITS:literal, $AdaptiveTestPrefix:literal) => {
104 /// Calculates the complete product `self * rhs` without the possibility to overflow.
106 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
107 /// of the result as two separate values, in that order.
113 /// Please note that this example is shared between integer types.
114 /// Which explains why `u32` is used here.
117 /// #![feature(bigint_helper_methods)]
118 /// assert_eq!(5u32.widening_mul(2), (10, 0));
119 /// assert_eq!(1_000_000_000u32.widening_mul(10), (1410065408, 2));
121 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
122 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
123 #[must_use = "this returns the result of the operation, \
124 without modifying the original"]
126 pub const fn widening_mul(self, rhs: Self) -> (Self, Self) {
127 // note: longer-term this should be done via an intrinsic,
128 // but for now we can deal without an impl for u128/i128
129 // SAFETY: overflow will be contained within the wider types
130 let wide = unsafe { (self as $WideT).unchecked_mul(rhs as $WideT) };
131 (wide as $SelfT, (wide >> $BITS) as $SelfT)
134 /// Calculates the "full multiplication" `self * rhs + carry`
135 /// without the possibility to overflow.
137 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
138 /// of the result as two separate values, in that order.
140 /// Performs "long multiplication" which takes in an extra amount to add, and may return an
141 /// additional amount of overflow. This allows for chaining together multiple
142 /// multiplications to create "big integers" which represent larger values.
148 /// Please note that this example is shared between integer types.
149 /// Which explains why `u32` is used here.
152 /// #![feature(bigint_helper_methods)]
153 /// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
154 /// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
155 /// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
156 /// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
157 #[doc = concat!($AdaptiveTestPrefix, "assert_eq!(",
158 stringify!($SelfT), "::MAX.carrying_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
159 "(0, ", stringify!($SelfT), "::MAX));"
163 /// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
164 /// except that it gives the value of the overflow instead of just whether one happened:
167 /// #![feature(bigint_helper_methods)]
168 /// let r = u8::carrying_mul(7, 13, 0);
169 /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
170 /// let r = u8::carrying_mul(13, 42, 0);
171 /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
174 /// The value of the first field in the returned tuple matches what you'd get
175 /// by combining the [`wrapping_mul`](Self::wrapping_mul) and
176 /// [`wrapping_add`](Self::wrapping_add) methods:
179 /// #![feature(bigint_helper_methods)]
181 /// 789_u16.carrying_mul(456, 123).0,
182 /// 789_u16.wrapping_mul(456).wrapping_add(123),
185 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
186 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
187 #[must_use = "this returns the result of the operation, \
188 without modifying the original"]
190 pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
191 // note: longer-term this should be done via an intrinsic,
192 // but for now we can deal without an impl for u128/i128
193 // SAFETY: overflow will be contained within the wider types
195 (self as $WideT).unchecked_mul(rhs as $WideT).unchecked_add(carry as $WideT)
197 (wide as $SelfT, (wide >> $BITS) as $SelfT)
204 int_impl! { i8, i8, u8, 8, 7, -128, 127, 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
205 "[0x12]", "[0x12]", "", "" }
206 widening_impl! { i8, i16, 8, signed }
211 int_impl! { i16, i16, u16, 16, 15, -32768, 32767, 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
212 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
213 widening_impl! { i16, i32, 16, signed }
218 int_impl! { i32, i32, u32, 32, 31, -2147483648, 2147483647, 8, "0x10000b3", "0xb301",
219 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
220 "[0x12, 0x34, 0x56, 0x78]", "", "" }
221 widening_impl! { i32, i64, 32, signed }
226 int_impl! { i64, i64, u64, 64, 63, -9223372036854775808, 9223372036854775807, 12,
227 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
228 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
229 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
230 widening_impl! { i64, i128, 64, signed }
235 int_impl! { i128, i128, u128, 128, 127, -170141183460469231731687303715884105728,
236 170141183460469231731687303715884105727, 16,
237 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
238 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
239 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
240 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
241 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
242 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
245 #[cfg(target_pointer_width = "16")]
248 int_impl! { isize, i16, usize, 16, 15, -32768, 32767, 4, "-0x5ffd", "0x3a", "0x1234",
249 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
250 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
251 widening_impl! { isize, i32, 16, signed }
254 #[cfg(target_pointer_width = "32")]
257 int_impl! { isize, i32, usize, 32, 31, -2147483648, 2147483647, 8, "0x10000b3", "0xb301",
258 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
259 "[0x12, 0x34, 0x56, 0x78]",
260 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
261 widening_impl! { isize, i64, 32, signed }
264 #[cfg(target_pointer_width = "64")]
267 int_impl! { isize, i64, usize, 64, 63, -9223372036854775808, 9223372036854775807,
268 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
269 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
270 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
271 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
272 widening_impl! { isize, i128, 64, signed }
275 /// If 6th bit set ascii is upper case.
276 const ASCII_CASE_MASK: u8 = 0b0010_0000;
280 uint_impl! { u8, u8, i8, 8, 255, 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
282 widening_impl! { u8, u16, 8, unsigned }
284 /// Checks if the value is within the ASCII range.
289 /// let ascii = 97u8;
290 /// let non_ascii = 150u8;
292 /// assert!(ascii.is_ascii());
293 /// assert!(!non_ascii.is_ascii());
296 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
297 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")]
299 pub const fn is_ascii(&self) -> bool {
303 /// Makes a copy of the value in its ASCII upper case equivalent.
305 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
306 /// but non-ASCII letters are unchanged.
308 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
313 /// let lowercase_a = 97u8;
315 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
318 /// [`make_ascii_uppercase`]: Self::make_ascii_uppercase
319 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
320 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
321 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
323 pub const fn to_ascii_uppercase(&self) -> u8 {
324 // Unset the fifth bit if this is a lowercase letter
325 *self & !((self.is_ascii_lowercase() as u8) * ASCII_CASE_MASK)
328 /// Makes a copy of the value in its ASCII lower case equivalent.
330 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
331 /// but non-ASCII letters are unchanged.
333 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
338 /// let uppercase_a = 65u8;
340 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
343 /// [`make_ascii_lowercase`]: Self::make_ascii_lowercase
344 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
345 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
346 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
348 pub const fn to_ascii_lowercase(&self) -> u8 {
349 // Set the fifth bit if this is an uppercase letter
350 *self | (self.is_ascii_uppercase() as u8 * ASCII_CASE_MASK)
353 /// Assumes self is ascii
355 pub(crate) const fn ascii_change_case_unchecked(&self) -> u8 {
356 *self ^ ASCII_CASE_MASK
359 /// Checks that two values are an ASCII case-insensitive match.
361 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
366 /// let lowercase_a = 97u8;
367 /// let uppercase_a = 65u8;
369 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
371 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
372 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
374 pub const fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
375 self.to_ascii_lowercase() == other.to_ascii_lowercase()
378 /// Converts this value to its ASCII upper case equivalent in-place.
380 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
381 /// but non-ASCII letters are unchanged.
383 /// To return a new uppercased value without modifying the existing one, use
384 /// [`to_ascii_uppercase`].
389 /// let mut byte = b'a';
391 /// byte.make_ascii_uppercase();
393 /// assert_eq!(b'A', byte);
396 /// [`to_ascii_uppercase`]: Self::to_ascii_uppercase
397 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
399 pub fn make_ascii_uppercase(&mut self) {
400 *self = self.to_ascii_uppercase();
403 /// Converts this value to its ASCII lower case equivalent in-place.
405 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
406 /// but non-ASCII letters are unchanged.
408 /// To return a new lowercased value without modifying the existing one, use
409 /// [`to_ascii_lowercase`].
414 /// let mut byte = b'A';
416 /// byte.make_ascii_lowercase();
418 /// assert_eq!(b'a', byte);
421 /// [`to_ascii_lowercase`]: Self::to_ascii_lowercase
422 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
424 pub fn make_ascii_lowercase(&mut self) {
425 *self = self.to_ascii_lowercase();
428 /// Checks if the value is an ASCII alphabetic character:
430 /// - U+0041 'A' ..= U+005A 'Z', or
431 /// - U+0061 'a' ..= U+007A 'z'.
436 /// let uppercase_a = b'A';
437 /// let uppercase_g = b'G';
441 /// let percent = b'%';
442 /// let space = b' ';
444 /// let esc = 0x1b_u8;
446 /// assert!(uppercase_a.is_ascii_alphabetic());
447 /// assert!(uppercase_g.is_ascii_alphabetic());
448 /// assert!(a.is_ascii_alphabetic());
449 /// assert!(g.is_ascii_alphabetic());
450 /// assert!(!zero.is_ascii_alphabetic());
451 /// assert!(!percent.is_ascii_alphabetic());
452 /// assert!(!space.is_ascii_alphabetic());
453 /// assert!(!lf.is_ascii_alphabetic());
454 /// assert!(!esc.is_ascii_alphabetic());
457 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
458 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
460 pub const fn is_ascii_alphabetic(&self) -> bool {
461 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
464 /// Checks if the value is an ASCII uppercase character:
465 /// U+0041 'A' ..= U+005A 'Z'.
470 /// let uppercase_a = b'A';
471 /// let uppercase_g = b'G';
475 /// let percent = b'%';
476 /// let space = b' ';
478 /// let esc = 0x1b_u8;
480 /// assert!(uppercase_a.is_ascii_uppercase());
481 /// assert!(uppercase_g.is_ascii_uppercase());
482 /// assert!(!a.is_ascii_uppercase());
483 /// assert!(!g.is_ascii_uppercase());
484 /// assert!(!zero.is_ascii_uppercase());
485 /// assert!(!percent.is_ascii_uppercase());
486 /// assert!(!space.is_ascii_uppercase());
487 /// assert!(!lf.is_ascii_uppercase());
488 /// assert!(!esc.is_ascii_uppercase());
491 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
492 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
494 pub const fn is_ascii_uppercase(&self) -> bool {
495 matches!(*self, b'A'..=b'Z')
498 /// Checks if the value is an ASCII lowercase character:
499 /// U+0061 'a' ..= U+007A 'z'.
504 /// let uppercase_a = b'A';
505 /// let uppercase_g = b'G';
509 /// let percent = b'%';
510 /// let space = b' ';
512 /// let esc = 0x1b_u8;
514 /// assert!(!uppercase_a.is_ascii_lowercase());
515 /// assert!(!uppercase_g.is_ascii_lowercase());
516 /// assert!(a.is_ascii_lowercase());
517 /// assert!(g.is_ascii_lowercase());
518 /// assert!(!zero.is_ascii_lowercase());
519 /// assert!(!percent.is_ascii_lowercase());
520 /// assert!(!space.is_ascii_lowercase());
521 /// assert!(!lf.is_ascii_lowercase());
522 /// assert!(!esc.is_ascii_lowercase());
525 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
526 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
528 pub const fn is_ascii_lowercase(&self) -> bool {
529 matches!(*self, b'a'..=b'z')
532 /// Checks if the value is an ASCII alphanumeric character:
534 /// - U+0041 'A' ..= U+005A 'Z', or
535 /// - U+0061 'a' ..= U+007A 'z', or
536 /// - U+0030 '0' ..= U+0039 '9'.
541 /// let uppercase_a = b'A';
542 /// let uppercase_g = b'G';
546 /// let percent = b'%';
547 /// let space = b' ';
549 /// let esc = 0x1b_u8;
551 /// assert!(uppercase_a.is_ascii_alphanumeric());
552 /// assert!(uppercase_g.is_ascii_alphanumeric());
553 /// assert!(a.is_ascii_alphanumeric());
554 /// assert!(g.is_ascii_alphanumeric());
555 /// assert!(zero.is_ascii_alphanumeric());
556 /// assert!(!percent.is_ascii_alphanumeric());
557 /// assert!(!space.is_ascii_alphanumeric());
558 /// assert!(!lf.is_ascii_alphanumeric());
559 /// assert!(!esc.is_ascii_alphanumeric());
562 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
563 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
565 pub const fn is_ascii_alphanumeric(&self) -> bool {
566 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
569 /// Checks if the value is an ASCII decimal digit:
570 /// U+0030 '0' ..= U+0039 '9'.
575 /// let uppercase_a = b'A';
576 /// let uppercase_g = b'G';
580 /// let percent = b'%';
581 /// let space = b' ';
583 /// let esc = 0x1b_u8;
585 /// assert!(!uppercase_a.is_ascii_digit());
586 /// assert!(!uppercase_g.is_ascii_digit());
587 /// assert!(!a.is_ascii_digit());
588 /// assert!(!g.is_ascii_digit());
589 /// assert!(zero.is_ascii_digit());
590 /// assert!(!percent.is_ascii_digit());
591 /// assert!(!space.is_ascii_digit());
592 /// assert!(!lf.is_ascii_digit());
593 /// assert!(!esc.is_ascii_digit());
596 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
597 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
599 pub const fn is_ascii_digit(&self) -> bool {
600 matches!(*self, b'0'..=b'9')
603 /// Checks if the value is an ASCII hexadecimal digit:
605 /// - U+0030 '0' ..= U+0039 '9', or
606 /// - U+0041 'A' ..= U+0046 'F', or
607 /// - U+0061 'a' ..= U+0066 'f'.
612 /// let uppercase_a = b'A';
613 /// let uppercase_g = b'G';
617 /// let percent = b'%';
618 /// let space = b' ';
620 /// let esc = 0x1b_u8;
622 /// assert!(uppercase_a.is_ascii_hexdigit());
623 /// assert!(!uppercase_g.is_ascii_hexdigit());
624 /// assert!(a.is_ascii_hexdigit());
625 /// assert!(!g.is_ascii_hexdigit());
626 /// assert!(zero.is_ascii_hexdigit());
627 /// assert!(!percent.is_ascii_hexdigit());
628 /// assert!(!space.is_ascii_hexdigit());
629 /// assert!(!lf.is_ascii_hexdigit());
630 /// assert!(!esc.is_ascii_hexdigit());
633 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
634 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
636 pub const fn is_ascii_hexdigit(&self) -> bool {
637 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
640 /// Checks if the value is an ASCII punctuation character:
642 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
643 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
644 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
645 /// - U+007B ..= U+007E `{ | } ~`
650 /// let uppercase_a = b'A';
651 /// let uppercase_g = b'G';
655 /// let percent = b'%';
656 /// let space = b' ';
658 /// let esc = 0x1b_u8;
660 /// assert!(!uppercase_a.is_ascii_punctuation());
661 /// assert!(!uppercase_g.is_ascii_punctuation());
662 /// assert!(!a.is_ascii_punctuation());
663 /// assert!(!g.is_ascii_punctuation());
664 /// assert!(!zero.is_ascii_punctuation());
665 /// assert!(percent.is_ascii_punctuation());
666 /// assert!(!space.is_ascii_punctuation());
667 /// assert!(!lf.is_ascii_punctuation());
668 /// assert!(!esc.is_ascii_punctuation());
671 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
672 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
674 pub const fn is_ascii_punctuation(&self) -> bool {
675 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
678 /// Checks if the value is an ASCII graphic character:
679 /// U+0021 '!' ..= U+007E '~'.
684 /// let uppercase_a = b'A';
685 /// let uppercase_g = b'G';
689 /// let percent = b'%';
690 /// let space = b' ';
692 /// let esc = 0x1b_u8;
694 /// assert!(uppercase_a.is_ascii_graphic());
695 /// assert!(uppercase_g.is_ascii_graphic());
696 /// assert!(a.is_ascii_graphic());
697 /// assert!(g.is_ascii_graphic());
698 /// assert!(zero.is_ascii_graphic());
699 /// assert!(percent.is_ascii_graphic());
700 /// assert!(!space.is_ascii_graphic());
701 /// assert!(!lf.is_ascii_graphic());
702 /// assert!(!esc.is_ascii_graphic());
705 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
706 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
708 pub const fn is_ascii_graphic(&self) -> bool {
709 matches!(*self, b'!'..=b'~')
712 /// Checks if the value is an ASCII whitespace character:
713 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
714 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
716 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
717 /// whitespace][infra-aw]. There are several other definitions in
718 /// wide use. For instance, [the POSIX locale][pct] includes
719 /// U+000B VERTICAL TAB as well as all the above characters,
720 /// but—from the very same specification—[the default rule for
721 /// "field splitting" in the Bourne shell][bfs] considers *only*
722 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
724 /// If you are writing a program that will process an existing
725 /// file format, check what that format's definition of whitespace is
726 /// before using this function.
728 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
729 /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
730 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
735 /// let uppercase_a = b'A';
736 /// let uppercase_g = b'G';
740 /// let percent = b'%';
741 /// let space = b' ';
743 /// let esc = 0x1b_u8;
745 /// assert!(!uppercase_a.is_ascii_whitespace());
746 /// assert!(!uppercase_g.is_ascii_whitespace());
747 /// assert!(!a.is_ascii_whitespace());
748 /// assert!(!g.is_ascii_whitespace());
749 /// assert!(!zero.is_ascii_whitespace());
750 /// assert!(!percent.is_ascii_whitespace());
751 /// assert!(space.is_ascii_whitespace());
752 /// assert!(lf.is_ascii_whitespace());
753 /// assert!(!esc.is_ascii_whitespace());
756 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
757 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
759 pub const fn is_ascii_whitespace(&self) -> bool {
760 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
763 /// Checks if the value is an ASCII control character:
764 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
765 /// Note that most ASCII whitespace characters are control
766 /// characters, but SPACE is not.
771 /// let uppercase_a = b'A';
772 /// let uppercase_g = b'G';
776 /// let percent = b'%';
777 /// let space = b' ';
779 /// let esc = 0x1b_u8;
781 /// assert!(!uppercase_a.is_ascii_control());
782 /// assert!(!uppercase_g.is_ascii_control());
783 /// assert!(!a.is_ascii_control());
784 /// assert!(!g.is_ascii_control());
785 /// assert!(!zero.is_ascii_control());
786 /// assert!(!percent.is_ascii_control());
787 /// assert!(!space.is_ascii_control());
788 /// assert!(lf.is_ascii_control());
789 /// assert!(esc.is_ascii_control());
792 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
793 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
795 pub const fn is_ascii_control(&self) -> bool {
796 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
799 /// Returns an iterator that produces an escaped version of a `u8`,
800 /// treating it as an ASCII character.
802 /// The behavior is identical to [`ascii::escape_default`].
807 /// #![feature(inherent_ascii_escape)]
809 /// assert_eq!("0", b'0'.escape_ascii().to_string());
810 /// assert_eq!("\\t", b'\t'.escape_ascii().to_string());
811 /// assert_eq!("\\r", b'\r'.escape_ascii().to_string());
812 /// assert_eq!("\\n", b'\n'.escape_ascii().to_string());
813 /// assert_eq!("\\'", b'\''.escape_ascii().to_string());
814 /// assert_eq!("\\\"", b'"'.escape_ascii().to_string());
815 /// assert_eq!("\\\\", b'\\'.escape_ascii().to_string());
816 /// assert_eq!("\\x9d", b'\x9d'.escape_ascii().to_string());
818 #[must_use = "this returns the escaped byte as an iterator, \
819 without modifying the original"]
820 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
822 pub fn escape_ascii(&self) -> ascii::EscapeDefault {
823 ascii::escape_default(*self)
829 uint_impl! { u16, u16, i16, 16, 65535, 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
830 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
831 widening_impl! { u16, u32, 16, unsigned }
836 uint_impl! { u32, u32, i32, 32, 4294967295, 8, "0x10000b3", "0xb301", "0x12345678",
837 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
838 widening_impl! { u32, u64, 32, unsigned }
843 uint_impl! { u64, u64, i64, 64, 18446744073709551615, 12, "0xaa00000000006e1", "0x6e10aa",
844 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
845 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
846 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
848 widening_impl! { u64, u128, 64, unsigned }
853 uint_impl! { u128, u128, i128, 128, 340282366920938463463374607431768211455, 16,
854 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
855 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
856 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
857 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
858 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
859 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
863 #[cfg(target_pointer_width = "16")]
866 uint_impl! { usize, u16, isize, 16, 65535, 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
867 "[0x34, 0x12]", "[0x12, 0x34]",
868 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
869 widening_impl! { usize, u32, 16, unsigned }
871 #[cfg(target_pointer_width = "32")]
874 uint_impl! { usize, u32, isize, 32, 4294967295, 8, "0x10000b3", "0xb301", "0x12345678",
875 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
876 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
877 widening_impl! { usize, u64, 32, unsigned }
880 #[cfg(target_pointer_width = "64")]
883 uint_impl! { usize, u64, isize, 64, 18446744073709551615, 12, "0xaa00000000006e1", "0x6e10aa",
884 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
885 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
886 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
887 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
888 widening_impl! { usize, u128, 64, unsigned }
891 /// A classification of floating point numbers.
893 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
894 /// their documentation for more.
899 /// use std::num::FpCategory;
901 /// let num = 12.4_f32;
902 /// let inf = f32::INFINITY;
904 /// let sub: f32 = 1.1754942e-38;
905 /// let nan = f32::NAN;
907 /// assert_eq!(num.classify(), FpCategory::Normal);
908 /// assert_eq!(inf.classify(), FpCategory::Infinite);
909 /// assert_eq!(zero.classify(), FpCategory::Zero);
910 /// assert_eq!(nan.classify(), FpCategory::Nan);
911 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
913 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
914 #[stable(feature = "rust1", since = "1.0.0")]
915 pub enum FpCategory {
916 /// NaN (not a number): this value results from calculations like `(-1.0).sqrt()`.
918 /// See [the documentation for `f32`](f32) for more information on the unusual properties
920 #[stable(feature = "rust1", since = "1.0.0")]
923 /// Positive or negative infinity, which often results from dividing a nonzero number
925 #[stable(feature = "rust1", since = "1.0.0")]
928 /// Positive or negative zero.
930 /// See [the documentation for `f32`](f32) for more information on the signedness of zeroes.
931 #[stable(feature = "rust1", since = "1.0.0")]
934 /// “Subnormal” or “denormal” floating point representation (less precise, relative to
935 /// their magnitude, than [`Normal`]).
937 /// Subnormal numbers are larger in magnitude than [`Zero`] but smaller in magnitude than all
938 /// [`Normal`] numbers.
940 /// [`Normal`]: Self::Normal
941 /// [`Zero`]: Self::Zero
942 #[stable(feature = "rust1", since = "1.0.0")]
945 /// A regular floating point number, not any of the exceptional categories.
947 /// The smallest positive normal numbers are [`f32::MIN_POSITIVE`] and [`f64::MIN_POSITIVE`],
948 /// and the largest positive normal numbers are [`f32::MAX`] and [`f64::MAX`]. (Unlike signed
949 /// integers, floating point numbers are symmetric in their range, so negating any of these
950 /// constants will produce their negative counterpart.)
951 #[stable(feature = "rust1", since = "1.0.0")]
956 trait FromStrRadixHelper: PartialOrd + Copy {
957 fn min_value() -> Self;
958 fn max_value() -> Self;
959 fn from_u32(u: u32) -> Self;
960 fn checked_mul(&self, other: u32) -> Option<Self>;
961 fn checked_sub(&self, other: u32) -> Option<Self>;
962 fn checked_add(&self, other: u32) -> Option<Self>;
965 macro_rules! from_str_radix_int_impl {
967 #[stable(feature = "rust1", since = "1.0.0")]
968 impl FromStr for $t {
969 type Err = ParseIntError;
970 fn from_str(src: &str) -> Result<Self, ParseIntError> {
971 from_str_radix(src, 10)
976 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
979 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
981 fn min_value() -> Self { Self::MIN }
983 fn max_value() -> Self { Self::MAX }
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 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
1002 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
1003 use self::IntErrorKind::*;
1004 use self::ParseIntError as PIE;
1007 (2..=36).contains(&radix),
1008 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1013 return Err(PIE { kind: Empty });
1016 let is_signed_ty = T::from_u32(0) > T::min_value();
1018 // all valid digits are ascii, so we will just iterate over the utf8 bytes
1019 // and cast them to chars. .to_digit() will safely return None for anything
1020 // other than a valid ascii digit for the given radix, including the first-byte
1021 // of multi-byte sequences
1022 let src = src.as_bytes();
1024 let (is_positive, digits) = match src[0] {
1025 b'+' | b'-' if src[1..].is_empty() => {
1026 return Err(PIE { kind: InvalidDigit });
1028 b'+' => (true, &src[1..]),
1029 b'-' if is_signed_ty => (false, &src[1..]),
1033 let mut result = T::from_u32(0);
1035 // The number is positive
1037 let x = match (c as char).to_digit(radix) {
1039 None => return Err(PIE { kind: InvalidDigit }),
1041 result = match result.checked_mul(radix) {
1042 Some(result) => result,
1043 None => return Err(PIE { kind: PosOverflow }),
1045 result = match result.checked_add(x) {
1046 Some(result) => result,
1047 None => return Err(PIE { kind: PosOverflow }),
1051 // The number is negative
1053 let x = match (c as char).to_digit(radix) {
1055 None => return Err(PIE { kind: InvalidDigit }),
1057 result = match result.checked_mul(radix) {
1058 Some(result) => result,
1059 None => return Err(PIE { kind: NegOverflow }),
1061 result = match result.checked_sub(x) {
1062 Some(result) => result,
1063 None => return Err(PIE { kind: NegOverflow }),