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) => {
98 /// Calculates the complete product `self * rhs` without the possibility to overflow.
100 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
101 /// of the result as two separate values, in that order.
107 /// Please note that this example is shared between integer types.
108 /// Which explains why `u32` is used here.
111 /// #![feature(bigint_helper_methods)]
112 /// assert_eq!(5u32.widening_mul(2), (10, 0));
113 /// assert_eq!(1_000_000_000u32.widening_mul(10), (1410065408, 2));
115 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
116 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
117 #[must_use = "this returns the result of the operation, \
118 without modifying the original"]
120 pub const fn widening_mul(self, rhs: Self) -> (Self, Self) {
121 // note: longer-term this should be done via an intrinsic,
122 // but for now we can deal without an impl for u128/i128
123 // SAFETY: overflow will be contained within the wider types
124 let wide = unsafe { (self as $WideT).unchecked_mul(rhs as $WideT) };
125 (wide as $SelfT, (wide >> $BITS) as $SelfT)
128 /// Calculates the "full multiplication" `self * rhs + carry`
129 /// without the possibility to overflow.
131 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
132 /// of the result as two separate values, in that order.
134 /// Performs "long multiplication" which takes in an extra amount to add, and may return an
135 /// additional amount of overflow. This allows for chaining together multiple
136 /// multiplications to create "big integers" which represent larger values.
142 /// Please note that this example is shared between integer types.
143 /// Which explains why `u32` is used here.
146 /// #![feature(bigint_helper_methods)]
147 /// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
148 /// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
149 /// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
150 /// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
152 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
153 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
154 #[must_use = "this returns the result of the operation, \
155 without modifying the original"]
157 pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
158 // note: longer-term this should be done via an intrinsic,
159 // but for now we can deal without an impl for u128/i128
160 // SAFETY: overflow will be contained within the wider types
162 (self as $WideT).unchecked_mul(rhs as $WideT).unchecked_add(carry as $WideT)
164 (wide as $SelfT, (wide >> $BITS) as $SelfT)
171 widening_impl! { i8, i16, 8 }
172 int_impl! { i8, i8, u8, 8, 7, -128, 127, 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
173 "[0x12]", "[0x12]", "", "" }
178 widening_impl! { i16, i32, 16 }
179 int_impl! { i16, i16, u16, 16, 15, -32768, 32767, 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
180 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
185 widening_impl! { i32, i64, 32 }
186 int_impl! { i32, i32, u32, 32, 31, -2147483648, 2147483647, 8, "0x10000b3", "0xb301",
187 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
188 "[0x12, 0x34, 0x56, 0x78]", "", "" }
193 widening_impl! { i64, i128, 64 }
194 int_impl! { i64, i64, u64, 64, 63, -9223372036854775808, 9223372036854775807, 12,
195 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
196 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
197 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
202 int_impl! { i128, i128, u128, 128, 127, -170141183460469231731687303715884105728,
203 170141183460469231731687303715884105727, 16,
204 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
205 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
206 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
207 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
208 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
209 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
212 #[cfg(target_pointer_width = "16")]
215 widening_impl! { isize, i32, 16 }
216 int_impl! { isize, i16, usize, 16, 15, -32768, 32767, 4, "-0x5ffd", "0x3a", "0x1234",
217 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
218 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
221 #[cfg(target_pointer_width = "32")]
224 widening_impl! { isize, i64, 32 }
225 int_impl! { isize, i32, usize, 32, 31, -2147483648, 2147483647, 8, "0x10000b3", "0xb301",
226 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
227 "[0x12, 0x34, 0x56, 0x78]",
228 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
231 #[cfg(target_pointer_width = "64")]
234 widening_impl! { isize, i128, 64 }
235 int_impl! { isize, i64, usize, 64, 63, -9223372036854775808, 9223372036854775807,
236 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
237 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
238 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
239 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
242 /// If 6th bit set ascii is upper case.
243 const ASCII_CASE_MASK: u8 = 0b0010_0000;
247 widening_impl! { u8, u16, 8 }
248 uint_impl! { u8, u8, i8, 8, 255, 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
251 /// Checks if the value is within the ASCII range.
256 /// let ascii = 97u8;
257 /// let non_ascii = 150u8;
259 /// assert!(ascii.is_ascii());
260 /// assert!(!non_ascii.is_ascii());
262 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
263 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")]
265 pub const fn is_ascii(&self) -> bool {
269 /// Makes a copy of the value in its ASCII upper case equivalent.
271 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
272 /// but non-ASCII letters are unchanged.
274 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
279 /// let lowercase_a = 97u8;
281 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
284 /// [`make_ascii_uppercase`]: Self::make_ascii_uppercase
285 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
286 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
288 pub const fn to_ascii_uppercase(&self) -> u8 {
289 // Unset the fifth bit if this is a lowercase letter
290 *self & !((self.is_ascii_lowercase() as u8) * ASCII_CASE_MASK)
293 /// Makes a copy of the value in its ASCII lower case equivalent.
295 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
296 /// but non-ASCII letters are unchanged.
298 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
303 /// let uppercase_a = 65u8;
305 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
308 /// [`make_ascii_lowercase`]: Self::make_ascii_lowercase
309 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
310 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
312 pub const fn to_ascii_lowercase(&self) -> u8 {
313 // Set the fifth bit if this is an uppercase letter
314 *self | (self.is_ascii_uppercase() as u8 * ASCII_CASE_MASK)
317 /// Assumes self is ascii
319 pub(crate) const fn ascii_change_case_unchecked(&self) -> u8 {
320 *self ^ ASCII_CASE_MASK
323 /// Checks that two values are an ASCII case-insensitive match.
325 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
330 /// let lowercase_a = 97u8;
331 /// let uppercase_a = 65u8;
333 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
335 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
336 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
338 pub const fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
339 self.to_ascii_lowercase() == other.to_ascii_lowercase()
342 /// Converts this value to its ASCII upper case equivalent in-place.
344 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
345 /// but non-ASCII letters are unchanged.
347 /// To return a new uppercased value without modifying the existing one, use
348 /// [`to_ascii_uppercase`].
353 /// let mut byte = b'a';
355 /// byte.make_ascii_uppercase();
357 /// assert_eq!(b'A', byte);
360 /// [`to_ascii_uppercase`]: Self::to_ascii_uppercase
361 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
363 pub fn make_ascii_uppercase(&mut self) {
364 *self = self.to_ascii_uppercase();
367 /// Converts this value to its ASCII lower case equivalent in-place.
369 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
370 /// but non-ASCII letters are unchanged.
372 /// To return a new lowercased value without modifying the existing one, use
373 /// [`to_ascii_lowercase`].
378 /// let mut byte = b'A';
380 /// byte.make_ascii_lowercase();
382 /// assert_eq!(b'a', byte);
385 /// [`to_ascii_lowercase`]: Self::to_ascii_lowercase
386 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
388 pub fn make_ascii_lowercase(&mut self) {
389 *self = self.to_ascii_lowercase();
392 /// Checks if the value is an ASCII alphabetic character:
394 /// - U+0041 'A' ..= U+005A 'Z', or
395 /// - U+0061 'a' ..= U+007A 'z'.
400 /// let uppercase_a = b'A';
401 /// let uppercase_g = b'G';
405 /// let percent = b'%';
406 /// let space = b' ';
408 /// let esc = 0x1b_u8;
410 /// assert!(uppercase_a.is_ascii_alphabetic());
411 /// assert!(uppercase_g.is_ascii_alphabetic());
412 /// assert!(a.is_ascii_alphabetic());
413 /// assert!(g.is_ascii_alphabetic());
414 /// assert!(!zero.is_ascii_alphabetic());
415 /// assert!(!percent.is_ascii_alphabetic());
416 /// assert!(!space.is_ascii_alphabetic());
417 /// assert!(!lf.is_ascii_alphabetic());
418 /// assert!(!esc.is_ascii_alphabetic());
420 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
421 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
423 pub const fn is_ascii_alphabetic(&self) -> bool {
424 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
427 /// Checks if the value is an ASCII uppercase character:
428 /// U+0041 'A' ..= U+005A 'Z'.
433 /// let uppercase_a = b'A';
434 /// let uppercase_g = b'G';
438 /// let percent = b'%';
439 /// let space = b' ';
441 /// let esc = 0x1b_u8;
443 /// assert!(uppercase_a.is_ascii_uppercase());
444 /// assert!(uppercase_g.is_ascii_uppercase());
445 /// assert!(!a.is_ascii_uppercase());
446 /// assert!(!g.is_ascii_uppercase());
447 /// assert!(!zero.is_ascii_uppercase());
448 /// assert!(!percent.is_ascii_uppercase());
449 /// assert!(!space.is_ascii_uppercase());
450 /// assert!(!lf.is_ascii_uppercase());
451 /// assert!(!esc.is_ascii_uppercase());
453 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
454 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
456 pub const fn is_ascii_uppercase(&self) -> bool {
457 matches!(*self, b'A'..=b'Z')
460 /// Checks if the value is an ASCII lowercase character:
461 /// U+0061 'a' ..= U+007A 'z'.
466 /// let uppercase_a = b'A';
467 /// let uppercase_g = b'G';
471 /// let percent = b'%';
472 /// let space = b' ';
474 /// let esc = 0x1b_u8;
476 /// assert!(!uppercase_a.is_ascii_lowercase());
477 /// assert!(!uppercase_g.is_ascii_lowercase());
478 /// assert!(a.is_ascii_lowercase());
479 /// assert!(g.is_ascii_lowercase());
480 /// assert!(!zero.is_ascii_lowercase());
481 /// assert!(!percent.is_ascii_lowercase());
482 /// assert!(!space.is_ascii_lowercase());
483 /// assert!(!lf.is_ascii_lowercase());
484 /// assert!(!esc.is_ascii_lowercase());
486 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
487 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
489 pub const fn is_ascii_lowercase(&self) -> bool {
490 matches!(*self, b'a'..=b'z')
493 /// Checks if the value is an ASCII alphanumeric character:
495 /// - U+0041 'A' ..= U+005A 'Z', or
496 /// - U+0061 'a' ..= U+007A 'z', or
497 /// - U+0030 '0' ..= U+0039 '9'.
502 /// let uppercase_a = b'A';
503 /// let uppercase_g = b'G';
507 /// let percent = b'%';
508 /// let space = b' ';
510 /// let esc = 0x1b_u8;
512 /// assert!(uppercase_a.is_ascii_alphanumeric());
513 /// assert!(uppercase_g.is_ascii_alphanumeric());
514 /// assert!(a.is_ascii_alphanumeric());
515 /// assert!(g.is_ascii_alphanumeric());
516 /// assert!(zero.is_ascii_alphanumeric());
517 /// assert!(!percent.is_ascii_alphanumeric());
518 /// assert!(!space.is_ascii_alphanumeric());
519 /// assert!(!lf.is_ascii_alphanumeric());
520 /// assert!(!esc.is_ascii_alphanumeric());
522 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
523 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
525 pub const fn is_ascii_alphanumeric(&self) -> bool {
526 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
529 /// Checks if the value is an ASCII decimal digit:
530 /// U+0030 '0' ..= U+0039 '9'.
535 /// let uppercase_a = b'A';
536 /// let uppercase_g = b'G';
540 /// let percent = b'%';
541 /// let space = b' ';
543 /// let esc = 0x1b_u8;
545 /// assert!(!uppercase_a.is_ascii_digit());
546 /// assert!(!uppercase_g.is_ascii_digit());
547 /// assert!(!a.is_ascii_digit());
548 /// assert!(!g.is_ascii_digit());
549 /// assert!(zero.is_ascii_digit());
550 /// assert!(!percent.is_ascii_digit());
551 /// assert!(!space.is_ascii_digit());
552 /// assert!(!lf.is_ascii_digit());
553 /// assert!(!esc.is_ascii_digit());
555 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
556 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
558 pub const fn is_ascii_digit(&self) -> bool {
559 matches!(*self, b'0'..=b'9')
562 /// Checks if the value is an ASCII hexadecimal digit:
564 /// - U+0030 '0' ..= U+0039 '9', or
565 /// - U+0041 'A' ..= U+0046 'F', or
566 /// - U+0061 'a' ..= U+0066 'f'.
571 /// let uppercase_a = b'A';
572 /// let uppercase_g = b'G';
576 /// let percent = b'%';
577 /// let space = b' ';
579 /// let esc = 0x1b_u8;
581 /// assert!(uppercase_a.is_ascii_hexdigit());
582 /// assert!(!uppercase_g.is_ascii_hexdigit());
583 /// assert!(a.is_ascii_hexdigit());
584 /// assert!(!g.is_ascii_hexdigit());
585 /// assert!(zero.is_ascii_hexdigit());
586 /// assert!(!percent.is_ascii_hexdigit());
587 /// assert!(!space.is_ascii_hexdigit());
588 /// assert!(!lf.is_ascii_hexdigit());
589 /// assert!(!esc.is_ascii_hexdigit());
591 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
592 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
594 pub const fn is_ascii_hexdigit(&self) -> bool {
595 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
598 /// Checks if the value is an ASCII punctuation character:
600 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
601 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
602 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
603 /// - U+007B ..= U+007E `{ | } ~`
608 /// let uppercase_a = b'A';
609 /// let uppercase_g = b'G';
613 /// let percent = b'%';
614 /// let space = b' ';
616 /// let esc = 0x1b_u8;
618 /// assert!(!uppercase_a.is_ascii_punctuation());
619 /// assert!(!uppercase_g.is_ascii_punctuation());
620 /// assert!(!a.is_ascii_punctuation());
621 /// assert!(!g.is_ascii_punctuation());
622 /// assert!(!zero.is_ascii_punctuation());
623 /// assert!(percent.is_ascii_punctuation());
624 /// assert!(!space.is_ascii_punctuation());
625 /// assert!(!lf.is_ascii_punctuation());
626 /// assert!(!esc.is_ascii_punctuation());
628 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
629 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
631 pub const fn is_ascii_punctuation(&self) -> bool {
632 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
635 /// Checks if the value is an ASCII graphic character:
636 /// U+0021 '!' ..= U+007E '~'.
641 /// let uppercase_a = b'A';
642 /// let uppercase_g = b'G';
646 /// let percent = b'%';
647 /// let space = b' ';
649 /// let esc = 0x1b_u8;
651 /// assert!(uppercase_a.is_ascii_graphic());
652 /// assert!(uppercase_g.is_ascii_graphic());
653 /// assert!(a.is_ascii_graphic());
654 /// assert!(g.is_ascii_graphic());
655 /// assert!(zero.is_ascii_graphic());
656 /// assert!(percent.is_ascii_graphic());
657 /// assert!(!space.is_ascii_graphic());
658 /// assert!(!lf.is_ascii_graphic());
659 /// assert!(!esc.is_ascii_graphic());
661 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
662 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
664 pub const fn is_ascii_graphic(&self) -> bool {
665 matches!(*self, b'!'..=b'~')
668 /// Checks if the value is an ASCII whitespace character:
669 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
670 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
672 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
673 /// whitespace][infra-aw]. There are several other definitions in
674 /// wide use. For instance, [the POSIX locale][pct] includes
675 /// U+000B VERTICAL TAB as well as all the above characters,
676 /// but—from the very same specification—[the default rule for
677 /// "field splitting" in the Bourne shell][bfs] considers *only*
678 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
680 /// If you are writing a program that will process an existing
681 /// file format, check what that format's definition of whitespace is
682 /// before using this function.
684 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
685 /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
686 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
691 /// let uppercase_a = b'A';
692 /// let uppercase_g = b'G';
696 /// let percent = b'%';
697 /// let space = b' ';
699 /// let esc = 0x1b_u8;
701 /// assert!(!uppercase_a.is_ascii_whitespace());
702 /// assert!(!uppercase_g.is_ascii_whitespace());
703 /// assert!(!a.is_ascii_whitespace());
704 /// assert!(!g.is_ascii_whitespace());
705 /// assert!(!zero.is_ascii_whitespace());
706 /// assert!(!percent.is_ascii_whitespace());
707 /// assert!(space.is_ascii_whitespace());
708 /// assert!(lf.is_ascii_whitespace());
709 /// assert!(!esc.is_ascii_whitespace());
711 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
712 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
714 pub const fn is_ascii_whitespace(&self) -> bool {
715 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
718 /// Checks if the value is an ASCII control character:
719 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
720 /// Note that most ASCII whitespace characters are control
721 /// characters, but SPACE is not.
726 /// let uppercase_a = b'A';
727 /// let uppercase_g = b'G';
731 /// let percent = b'%';
732 /// let space = b' ';
734 /// let esc = 0x1b_u8;
736 /// assert!(!uppercase_a.is_ascii_control());
737 /// assert!(!uppercase_g.is_ascii_control());
738 /// assert!(!a.is_ascii_control());
739 /// assert!(!g.is_ascii_control());
740 /// assert!(!zero.is_ascii_control());
741 /// assert!(!percent.is_ascii_control());
742 /// assert!(!space.is_ascii_control());
743 /// assert!(lf.is_ascii_control());
744 /// assert!(esc.is_ascii_control());
746 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
747 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
749 pub const fn is_ascii_control(&self) -> bool {
750 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
753 /// Returns an iterator that produces an escaped version of a `u8`,
754 /// treating it as an ASCII character.
756 /// The behavior is identical to [`ascii::escape_default`].
761 /// #![feature(inherent_ascii_escape)]
763 /// assert_eq!("0", b'0'.escape_ascii().to_string());
764 /// assert_eq!("\\t", b'\t'.escape_ascii().to_string());
765 /// assert_eq!("\\r", b'\r'.escape_ascii().to_string());
766 /// assert_eq!("\\n", b'\n'.escape_ascii().to_string());
767 /// assert_eq!("\\'", b'\''.escape_ascii().to_string());
768 /// assert_eq!("\\\"", b'"'.escape_ascii().to_string());
769 /// assert_eq!("\\\\", b'\\'.escape_ascii().to_string());
770 /// assert_eq!("\\x9d", b'\x9d'.escape_ascii().to_string());
772 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
774 pub fn escape_ascii(&self) -> ascii::EscapeDefault {
775 ascii::escape_default(*self)
781 widening_impl! { u16, u32, 16 }
782 uint_impl! { u16, u16, i16, 16, 65535, 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
783 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
788 widening_impl! { u32, u64, 32 }
789 uint_impl! { u32, u32, i32, 32, 4294967295, 8, "0x10000b3", "0xb301", "0x12345678",
790 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
795 widening_impl! { u64, u128, 64 }
796 uint_impl! { u64, u64, i64, 64, 18446744073709551615, 12, "0xaa00000000006e1", "0x6e10aa",
797 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
798 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
799 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
805 uint_impl! { u128, u128, i128, 128, 340282366920938463463374607431768211455, 16,
806 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
807 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
808 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
809 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
810 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
811 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
815 #[cfg(target_pointer_width = "16")]
818 widening_impl! { usize, u32, 16 }
819 uint_impl! { usize, u16, isize, 16, 65535, 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
820 "[0x34, 0x12]", "[0x12, 0x34]",
821 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
823 #[cfg(target_pointer_width = "32")]
826 widening_impl! { usize, u64, 32 }
827 uint_impl! { usize, u32, isize, 32, 4294967295, 8, "0x10000b3", "0xb301", "0x12345678",
828 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
829 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
832 #[cfg(target_pointer_width = "64")]
835 widening_impl! { usize, u128, 64 }
836 uint_impl! { usize, u64, isize, 64, 18446744073709551615, 12, "0xaa00000000006e1", "0x6e10aa",
837 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
838 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
839 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
840 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
843 /// A classification of floating point numbers.
845 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
846 /// their documentation for more.
851 /// use std::num::FpCategory;
853 /// let num = 12.4_f32;
854 /// let inf = f32::INFINITY;
856 /// let sub: f32 = 1.1754942e-38;
857 /// let nan = f32::NAN;
859 /// assert_eq!(num.classify(), FpCategory::Normal);
860 /// assert_eq!(inf.classify(), FpCategory::Infinite);
861 /// assert_eq!(zero.classify(), FpCategory::Zero);
862 /// assert_eq!(nan.classify(), FpCategory::Nan);
863 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
865 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
866 #[stable(feature = "rust1", since = "1.0.0")]
867 pub enum FpCategory {
868 /// NaN (not a number): this value results from calculations like `(-1.0).sqrt()`.
870 /// See [the documentation for `f32`](f32) for more information on the unusual properties
872 #[stable(feature = "rust1", since = "1.0.0")]
875 /// Positive or negative infinity, which often results from dividing a nonzero number
877 #[stable(feature = "rust1", since = "1.0.0")]
880 /// Positive or negative zero.
882 /// See [the documentation for `f32`](f32) for more information on the signedness of zeroes.
883 #[stable(feature = "rust1", since = "1.0.0")]
886 /// “Subnormal” or “denormal” floating point representation (less precise, relative to
887 /// their magnitude, than [`Normal`]).
889 /// Subnormal numbers are larger in magnitude than [`Zero`] but smaller in magnitude than all
890 /// [`Normal`] numbers.
892 /// [`Normal`]: Self::Normal
893 /// [`Zero`]: Self::Zero
894 #[stable(feature = "rust1", since = "1.0.0")]
897 /// A regular floating point number, not any of the exceptional categories.
899 /// The smallest positive normal numbers are [`f32::MIN_POSITIVE`] and [`f64::MIN_POSITIVE`],
900 /// and the largest positive normal numbers are [`f32::MAX`] and [`f64::MAX`]. (Unlike signed
901 /// integers, floating point numbers are symmetric in their range, so negating any of these
902 /// constants will produce their negative counterpart.)
903 #[stable(feature = "rust1", since = "1.0.0")]
908 trait FromStrRadixHelper: PartialOrd + Copy {
909 fn min_value() -> Self;
910 fn max_value() -> Self;
911 fn from_u32(u: u32) -> Self;
912 fn checked_mul(&self, other: u32) -> Option<Self>;
913 fn checked_sub(&self, other: u32) -> Option<Self>;
914 fn checked_add(&self, other: u32) -> Option<Self>;
917 macro_rules! from_str_radix_int_impl {
919 #[stable(feature = "rust1", since = "1.0.0")]
920 impl FromStr for $t {
921 type Err = ParseIntError;
922 fn from_str(src: &str) -> Result<Self, ParseIntError> {
923 from_str_radix(src, 10)
928 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
931 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
933 fn min_value() -> Self { Self::MIN }
935 fn max_value() -> Self { Self::MAX }
937 fn from_u32(u: u32) -> Self { u as Self }
939 fn checked_mul(&self, other: u32) -> Option<Self> {
940 Self::checked_mul(*self, other as Self)
943 fn checked_sub(&self, other: u32) -> Option<Self> {
944 Self::checked_sub(*self, other as Self)
947 fn checked_add(&self, other: u32) -> Option<Self> {
948 Self::checked_add(*self, other as Self)
952 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
954 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
955 use self::IntErrorKind::*;
956 use self::ParseIntError as PIE;
959 (2..=36).contains(&radix),
960 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
965 return Err(PIE { kind: Empty });
968 let is_signed_ty = T::from_u32(0) > T::min_value();
970 // all valid digits are ascii, so we will just iterate over the utf8 bytes
971 // and cast them to chars. .to_digit() will safely return None for anything
972 // other than a valid ascii digit for the given radix, including the first-byte
973 // of multi-byte sequences
974 let src = src.as_bytes();
976 let (is_positive, digits) = match src[0] {
977 b'+' | b'-' if src[1..].is_empty() => {
978 return Err(PIE { kind: InvalidDigit });
980 b'+' => (true, &src[1..]),
981 b'-' if is_signed_ty => (false, &src[1..]),
985 let mut result = T::from_u32(0);
987 // The number is positive
989 let x = match (c as char).to_digit(radix) {
991 None => return Err(PIE { kind: InvalidDigit }),
993 result = match result.checked_mul(radix) {
994 Some(result) => result,
995 None => return Err(PIE { kind: PosOverflow }),
997 result = match result.checked_add(x) {
998 Some(result) => result,
999 None => return Err(PIE { kind: PosOverflow }),
1003 // The number is negative
1005 let x = match (c as char).to_digit(radix) {
1007 None => return Err(PIE { kind: InvalidDigit }),
1009 result = match result.checked_mul(radix) {
1010 Some(result) => result,
1011 None => return Err(PIE { kind: NegOverflow }),
1013 result = match result.checked_sub(x) {
1014 Some(result) => result,
1015 None => return Err(PIE { kind: NegOverflow }),