]> git.lizzy.rs Git - rust.git/blob - library/core/src/num/mod.rs
Auto merge of #90604 - mbartlett21:iterator-reexports, r=kennytm
[rust.git] / library / core / src / num / mod.rs
1 //! Numeric traits and functions for the built-in numeric types.
2
3 #![stable(feature = "rust1", since = "1.0.0")]
4
5 use crate::ascii;
6 use crate::intrinsics;
7 use crate::mem;
8 use crate::str::FromStr;
9
10 // Used because the `?` operator is not allowed in a const context.
11 macro_rules! try_opt {
12     ($e:expr) => {
13         match $e {
14             Some(x) => x,
15             None => return None,
16         }
17     };
18 }
19
20 #[allow_internal_unstable(const_likely)]
21 macro_rules! unlikely {
22     ($e: expr) => {
23         intrinsics::unlikely($e)
24     };
25 }
26
27 // All these modules are technically private and only exposed for coretests:
28 #[cfg(not(no_fp_fmt_parse))]
29 pub mod bignum;
30 #[cfg(not(no_fp_fmt_parse))]
31 pub mod dec2flt;
32 #[cfg(not(no_fp_fmt_parse))]
33 pub mod diy_float;
34 #[cfg(not(no_fp_fmt_parse))]
35 pub mod flt2dec;
36 pub mod fmt;
37
38 #[macro_use]
39 mod int_macros; // import int_impl!
40 #[macro_use]
41 mod uint_macros; // import uint_impl!
42
43 mod error;
44 mod int_log10;
45 mod nonzero;
46 #[unstable(feature = "saturating_int_impl", issue = "87920")]
47 mod saturating;
48 mod wrapping;
49
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;
54
55 #[stable(feature = "rust1", since = "1.0.0")]
56 #[cfg(not(no_fp_fmt_parse))]
57 pub use dec2flt::ParseFloatError;
58
59 #[stable(feature = "rust1", since = "1.0.0")]
60 pub use error::ParseIntError;
61
62 #[stable(feature = "nonzero", since = "1.28.0")]
63 pub use nonzero::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize};
64
65 #[stable(feature = "signed_nonzero", since = "1.34.0")]
66 pub use nonzero::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize};
67
68 #[stable(feature = "try_from", since = "1.34.0")]
69 pub use error::TryFromIntError;
70
71 #[stable(feature = "int_error_matching", since = "1.55.0")]
72 pub use error::IntErrorKind;
73
74 macro_rules! usize_isize_to_xe_bytes_doc {
75     () => {
76         "
77
78 **Note**: This function returns an array of length 2, 4 or 8 bytes
79 depending on the target pointer size.
80
81 "
82     };
83 }
84
85 macro_rules! usize_isize_from_xe_bytes_doc {
86     () => {
87         "
88
89 **Note**: This function takes an array of length 2, 4 or 8 bytes
90 depending on the target pointer size.
91
92 "
93     };
94 }
95
96 macro_rules! widening_impl {
97     ($SelfT:ty, $WideT:ty, $BITS:literal, unsigned) => {
98         widening_impl!($SelfT, $WideT, $BITS, "");
99     };
100     ($SelfT:ty, $WideT:ty, $BITS:literal, signed) => {
101         widening_impl!($SelfT, $WideT, $BITS, "# //");
102     };
103     ($SelfT:ty, $WideT:ty, $BITS:literal, $AdaptiveTestPrefix:literal) => {
104         /// Calculates the complete product `self * rhs` without the possibility to overflow.
105         ///
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.
108         ///
109         /// # Examples
110         ///
111         /// Basic usage:
112         ///
113         /// Please note that this example is shared between integer types.
114         /// Which explains why `u32` is used here.
115         ///
116         /// ```
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));
120         /// ```
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"]
125         #[inline]
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)
132         }
133
134         /// Calculates the "full multiplication" `self * rhs + carry`
135         /// without the possibility to overflow.
136         ///
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.
139         ///
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.
143         ///
144         /// # Examples
145         ///
146         /// Basic usage:
147         ///
148         /// Please note that this example is shared between integer types.
149         /// Which explains why `u32` is used here.
150         ///
151         /// ```
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));"
160         )]
161         /// ```
162         ///
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:
165         ///
166         /// ```
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));
172         /// ```
173         ///
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:
177         ///
178         /// ```
179         /// #![feature(bigint_helper_methods)]
180         /// assert_eq!(
181         ///     789_u16.carrying_mul(456, 123).0,
182         ///     789_u16.wrapping_mul(456).wrapping_add(123),
183         /// );
184         /// ```
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"]
189         #[inline]
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
194             let wide = unsafe {
195                 (self as $WideT).unchecked_mul(rhs as $WideT).unchecked_add(carry as $WideT)
196             };
197             (wide as $SelfT, (wide >> $BITS) as $SelfT)
198         }
199     };
200 }
201
202 #[lang = "i8"]
203 impl i8 {
204     widening_impl! { i8, i16, 8, signed }
205     int_impl! { i8, i8, u8, 8, 7, -128, 127, 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
206     "[0x12]", "[0x12]", "", "" }
207 }
208
209 #[lang = "i16"]
210 impl i16 {
211     widening_impl! { i16, i32, 16, signed }
212     int_impl! { i16, i16, u16, 16, 15, -32768, 32767, 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
213     "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
214 }
215
216 #[lang = "i32"]
217 impl i32 {
218     widening_impl! { i32, i64, 32, signed }
219     int_impl! { i32, i32, u32, 32, 31, -2147483648, 2147483647, 8, "0x10000b3", "0xb301",
220     "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
221     "[0x12, 0x34, 0x56, 0x78]", "", "" }
222 }
223
224 #[lang = "i64"]
225 impl i64 {
226     widening_impl! { i64, i128, 64, signed }
227     int_impl! { i64, i64, u64, 64, 63, -9223372036854775808, 9223372036854775807, 12,
228     "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
229     "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
230     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
231 }
232
233 #[lang = "i128"]
234 impl i128 {
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]", "", "" }
243 }
244
245 #[cfg(target_pointer_width = "16")]
246 #[lang = "isize"]
247 impl isize {
248     widening_impl! { isize, i32, 16, signed }
249     int_impl! { isize, i16, usize, 16, 15, -32768, 32767, 4, "-0x5ffd", "0x3a", "0x1234",
250     "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
251     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
252 }
253
254 #[cfg(target_pointer_width = "32")]
255 #[lang = "isize"]
256 impl isize {
257     widening_impl! { isize, i64, 32, signed }
258     int_impl! { isize, i32, usize, 32, 31, -2147483648, 2147483647, 8, "0x10000b3", "0xb301",
259     "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
260     "[0x12, 0x34, 0x56, 0x78]",
261     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
262 }
263
264 #[cfg(target_pointer_width = "64")]
265 #[lang = "isize"]
266 impl isize {
267     widening_impl! { isize, i128, 64, signed }
268     int_impl! { isize, i64, usize, 64, 63, -9223372036854775808, 9223372036854775807,
269     12, "0xaa00000000006e1", "0x6e10aa",  "0x1234567890123456", "0x5634129078563412",
270      "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
271      "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
272      usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
273 }
274
275 /// If 6th bit set ascii is upper case.
276 const ASCII_CASE_MASK: u8 = 0b0010_0000;
277
278 #[lang = "u8"]
279 impl u8 {
280     widening_impl! { u8, u16, 8, unsigned }
281     uint_impl! { u8, u8, i8, 8, 255, 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
282     "[0x12]", "", "" }
283
284     /// Checks if the value is within the ASCII range.
285     ///
286     /// # Examples
287     ///
288     /// ```
289     /// let ascii = 97u8;
290     /// let non_ascii = 150u8;
291     ///
292     /// assert!(ascii.is_ascii());
293     /// assert!(!non_ascii.is_ascii());
294     /// ```
295     #[must_use]
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")]
298     #[inline]
299     pub const fn is_ascii(&self) -> bool {
300         *self & 128 == 0
301     }
302
303     /// Makes a copy of the value in its ASCII upper case equivalent.
304     ///
305     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
306     /// but non-ASCII letters are unchanged.
307     ///
308     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
309     ///
310     /// # Examples
311     ///
312     /// ```
313     /// let lowercase_a = 97u8;
314     ///
315     /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
316     /// ```
317     ///
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")]
322     #[inline]
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)
326     }
327
328     /// Makes a copy of the value in its ASCII lower case equivalent.
329     ///
330     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
331     /// but non-ASCII letters are unchanged.
332     ///
333     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
334     ///
335     /// # Examples
336     ///
337     /// ```
338     /// let uppercase_a = 65u8;
339     ///
340     /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
341     /// ```
342     ///
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")]
347     #[inline]
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)
351     }
352
353     /// Assumes self is ascii
354     #[inline]
355     pub(crate) const fn ascii_change_case_unchecked(&self) -> u8 {
356         *self ^ ASCII_CASE_MASK
357     }
358
359     /// Checks that two values are an ASCII case-insensitive match.
360     ///
361     /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
362     ///
363     /// # Examples
364     ///
365     /// ```
366     /// let lowercase_a = 97u8;
367     /// let uppercase_a = 65u8;
368     ///
369     /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
370     /// ```
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")]
373     #[inline]
374     pub const fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
375         self.to_ascii_lowercase() == other.to_ascii_lowercase()
376     }
377
378     /// Converts this value to its ASCII upper case equivalent in-place.
379     ///
380     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
381     /// but non-ASCII letters are unchanged.
382     ///
383     /// To return a new uppercased value without modifying the existing one, use
384     /// [`to_ascii_uppercase`].
385     ///
386     /// # Examples
387     ///
388     /// ```
389     /// let mut byte = b'a';
390     ///
391     /// byte.make_ascii_uppercase();
392     ///
393     /// assert_eq!(b'A', byte);
394     /// ```
395     ///
396     /// [`to_ascii_uppercase`]: Self::to_ascii_uppercase
397     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
398     #[inline]
399     pub fn make_ascii_uppercase(&mut self) {
400         *self = self.to_ascii_uppercase();
401     }
402
403     /// Converts this value to its ASCII lower case equivalent in-place.
404     ///
405     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
406     /// but non-ASCII letters are unchanged.
407     ///
408     /// To return a new lowercased value without modifying the existing one, use
409     /// [`to_ascii_lowercase`].
410     ///
411     /// # Examples
412     ///
413     /// ```
414     /// let mut byte = b'A';
415     ///
416     /// byte.make_ascii_lowercase();
417     ///
418     /// assert_eq!(b'a', byte);
419     /// ```
420     ///
421     /// [`to_ascii_lowercase`]: Self::to_ascii_lowercase
422     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
423     #[inline]
424     pub fn make_ascii_lowercase(&mut self) {
425         *self = self.to_ascii_lowercase();
426     }
427
428     /// Checks if the value is an ASCII alphabetic character:
429     ///
430     /// - U+0041 'A' ..= U+005A 'Z', or
431     /// - U+0061 'a' ..= U+007A 'z'.
432     ///
433     /// # Examples
434     ///
435     /// ```
436     /// let uppercase_a = b'A';
437     /// let uppercase_g = b'G';
438     /// let a = b'a';
439     /// let g = b'g';
440     /// let zero = b'0';
441     /// let percent = b'%';
442     /// let space = b' ';
443     /// let lf = b'\n';
444     /// let esc = 0x1b_u8;
445     ///
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());
455     /// ```
456     #[must_use]
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")]
459     #[inline]
460     pub const fn is_ascii_alphabetic(&self) -> bool {
461         matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
462     }
463
464     /// Checks if the value is an ASCII uppercase character:
465     /// U+0041 'A' ..= U+005A 'Z'.
466     ///
467     /// # Examples
468     ///
469     /// ```
470     /// let uppercase_a = b'A';
471     /// let uppercase_g = b'G';
472     /// let a = b'a';
473     /// let g = b'g';
474     /// let zero = b'0';
475     /// let percent = b'%';
476     /// let space = b' ';
477     /// let lf = b'\n';
478     /// let esc = 0x1b_u8;
479     ///
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());
489     /// ```
490     #[must_use]
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")]
493     #[inline]
494     pub const fn is_ascii_uppercase(&self) -> bool {
495         matches!(*self, b'A'..=b'Z')
496     }
497
498     /// Checks if the value is an ASCII lowercase character:
499     /// U+0061 'a' ..= U+007A 'z'.
500     ///
501     /// # Examples
502     ///
503     /// ```
504     /// let uppercase_a = b'A';
505     /// let uppercase_g = b'G';
506     /// let a = b'a';
507     /// let g = b'g';
508     /// let zero = b'0';
509     /// let percent = b'%';
510     /// let space = b' ';
511     /// let lf = b'\n';
512     /// let esc = 0x1b_u8;
513     ///
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());
523     /// ```
524     #[must_use]
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")]
527     #[inline]
528     pub const fn is_ascii_lowercase(&self) -> bool {
529         matches!(*self, b'a'..=b'z')
530     }
531
532     /// Checks if the value is an ASCII alphanumeric character:
533     ///
534     /// - U+0041 'A' ..= U+005A 'Z', or
535     /// - U+0061 'a' ..= U+007A 'z', or
536     /// - U+0030 '0' ..= U+0039 '9'.
537     ///
538     /// # Examples
539     ///
540     /// ```
541     /// let uppercase_a = b'A';
542     /// let uppercase_g = b'G';
543     /// let a = b'a';
544     /// let g = b'g';
545     /// let zero = b'0';
546     /// let percent = b'%';
547     /// let space = b' ';
548     /// let lf = b'\n';
549     /// let esc = 0x1b_u8;
550     ///
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());
560     /// ```
561     #[must_use]
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")]
564     #[inline]
565     pub const fn is_ascii_alphanumeric(&self) -> bool {
566         matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
567     }
568
569     /// Checks if the value is an ASCII decimal digit:
570     /// U+0030 '0' ..= U+0039 '9'.
571     ///
572     /// # Examples
573     ///
574     /// ```
575     /// let uppercase_a = b'A';
576     /// let uppercase_g = b'G';
577     /// let a = b'a';
578     /// let g = b'g';
579     /// let zero = b'0';
580     /// let percent = b'%';
581     /// let space = b' ';
582     /// let lf = b'\n';
583     /// let esc = 0x1b_u8;
584     ///
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());
594     /// ```
595     #[must_use]
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")]
598     #[inline]
599     pub const fn is_ascii_digit(&self) -> bool {
600         matches!(*self, b'0'..=b'9')
601     }
602
603     /// Checks if the value is an ASCII hexadecimal digit:
604     ///
605     /// - U+0030 '0' ..= U+0039 '9', or
606     /// - U+0041 'A' ..= U+0046 'F', or
607     /// - U+0061 'a' ..= U+0066 'f'.
608     ///
609     /// # Examples
610     ///
611     /// ```
612     /// let uppercase_a = b'A';
613     /// let uppercase_g = b'G';
614     /// let a = b'a';
615     /// let g = b'g';
616     /// let zero = b'0';
617     /// let percent = b'%';
618     /// let space = b' ';
619     /// let lf = b'\n';
620     /// let esc = 0x1b_u8;
621     ///
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());
631     /// ```
632     #[must_use]
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")]
635     #[inline]
636     pub const fn is_ascii_hexdigit(&self) -> bool {
637         matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
638     }
639
640     /// Checks if the value is an ASCII punctuation character:
641     ///
642     /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
643     /// - U+003A ..= U+0040 `: ; < = > ? @`, or
644     /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
645     /// - U+007B ..= U+007E `{ | } ~`
646     ///
647     /// # Examples
648     ///
649     /// ```
650     /// let uppercase_a = b'A';
651     /// let uppercase_g = b'G';
652     /// let a = b'a';
653     /// let g = b'g';
654     /// let zero = b'0';
655     /// let percent = b'%';
656     /// let space = b' ';
657     /// let lf = b'\n';
658     /// let esc = 0x1b_u8;
659     ///
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());
669     /// ```
670     #[must_use]
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")]
673     #[inline]
674     pub const fn is_ascii_punctuation(&self) -> bool {
675         matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
676     }
677
678     /// Checks if the value is an ASCII graphic character:
679     /// U+0021 '!' ..= U+007E '~'.
680     ///
681     /// # Examples
682     ///
683     /// ```
684     /// let uppercase_a = b'A';
685     /// let uppercase_g = b'G';
686     /// let a = b'a';
687     /// let g = b'g';
688     /// let zero = b'0';
689     /// let percent = b'%';
690     /// let space = b' ';
691     /// let lf = b'\n';
692     /// let esc = 0x1b_u8;
693     ///
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());
703     /// ```
704     #[must_use]
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")]
707     #[inline]
708     pub const fn is_ascii_graphic(&self) -> bool {
709         matches!(*self, b'!'..=b'~')
710     }
711
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.
715     ///
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.
723     ///
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.
727     ///
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
731     ///
732     /// # Examples
733     ///
734     /// ```
735     /// let uppercase_a = b'A';
736     /// let uppercase_g = b'G';
737     /// let a = b'a';
738     /// let g = b'g';
739     /// let zero = b'0';
740     /// let percent = b'%';
741     /// let space = b' ';
742     /// let lf = b'\n';
743     /// let esc = 0x1b_u8;
744     ///
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());
754     /// ```
755     #[must_use]
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")]
758     #[inline]
759     pub const fn is_ascii_whitespace(&self) -> bool {
760         matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
761     }
762
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.
767     ///
768     /// # Examples
769     ///
770     /// ```
771     /// let uppercase_a = b'A';
772     /// let uppercase_g = b'G';
773     /// let a = b'a';
774     /// let g = b'g';
775     /// let zero = b'0';
776     /// let percent = b'%';
777     /// let space = b' ';
778     /// let lf = b'\n';
779     /// let esc = 0x1b_u8;
780     ///
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());
790     /// ```
791     #[must_use]
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")]
794     #[inline]
795     pub const fn is_ascii_control(&self) -> bool {
796         matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
797     }
798
799     /// Returns an iterator that produces an escaped version of a `u8`,
800     /// treating it as an ASCII character.
801     ///
802     /// The behavior is identical to [`ascii::escape_default`].
803     ///
804     /// # Examples
805     ///
806     /// ```
807     /// #![feature(inherent_ascii_escape)]
808     ///
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());
817     /// ```
818     #[must_use = "this returns the escaped byte as an iterator, \
819                   without modifying the original"]
820     #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
821     #[inline]
822     pub fn escape_ascii(&self) -> ascii::EscapeDefault {
823         ascii::escape_default(*self)
824     }
825 }
826
827 #[lang = "u16"]
828 impl u16 {
829     widening_impl! { u16, u32, 16, unsigned }
830     uint_impl! { u16, u16, i16, 16, 65535, 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
831     "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
832 }
833
834 #[lang = "u32"]
835 impl u32 {
836     widening_impl! { u32, u64, 32, unsigned }
837     uint_impl! { u32, u32, i32, 32, 4294967295, 8, "0x10000b3", "0xb301", "0x12345678",
838     "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
839 }
840
841 #[lang = "u64"]
842 impl u64 {
843     widening_impl! { u64, u128, 64, unsigned }
844     uint_impl! { u64, u64, i64, 64, 18446744073709551615, 12, "0xaa00000000006e1", "0x6e10aa",
845     "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
846     "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
847     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
848     "", ""}
849 }
850
851 #[lang = "u128"]
852 impl u128 {
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]",
860      "", ""}
861 }
862
863 #[cfg(target_pointer_width = "16")]
864 #[lang = "usize"]
865 impl usize {
866     widening_impl! { usize, u32, 16, unsigned }
867     uint_impl! { usize, u16, isize, 16, 65535, 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
868     "[0x34, 0x12]", "[0x12, 0x34]",
869     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
870 }
871 #[cfg(target_pointer_width = "32")]
872 #[lang = "usize"]
873 impl usize {
874     widening_impl! { usize, u64, 32, unsigned }
875     uint_impl! { usize, u32, isize, 32, 4294967295, 8, "0x10000b3", "0xb301", "0x12345678",
876     "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
877     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
878 }
879
880 #[cfg(target_pointer_width = "64")]
881 #[lang = "usize"]
882 impl usize {
883     widening_impl! { usize, u128, 64, unsigned }
884     uint_impl! { usize, u64, isize, 64, 18446744073709551615, 12, "0xaa00000000006e1", "0x6e10aa",
885     "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
886     "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
887      "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
888     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
889 }
890
891 /// A classification of floating point numbers.
892 ///
893 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
894 /// their documentation for more.
895 ///
896 /// # Examples
897 ///
898 /// ```
899 /// use std::num::FpCategory;
900 ///
901 /// let num = 12.4_f32;
902 /// let inf = f32::INFINITY;
903 /// let zero = 0f32;
904 /// let sub: f32 = 1.1754942e-38;
905 /// let nan = f32::NAN;
906 ///
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);
912 /// ```
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()`.
917     ///
918     /// See [the documentation for `f32`](f32) for more information on the unusual properties
919     /// of NaN.
920     #[stable(feature = "rust1", since = "1.0.0")]
921     Nan,
922
923     /// Positive or negative infinity, which often results from dividing a nonzero number
924     /// by zero.
925     #[stable(feature = "rust1", since = "1.0.0")]
926     Infinite,
927
928     /// Positive or negative zero.
929     ///
930     /// See [the documentation for `f32`](f32) for more information on the signedness of zeroes.
931     #[stable(feature = "rust1", since = "1.0.0")]
932     Zero,
933
934     /// “Subnormal” or “denormal” floating point representation (less precise, relative to
935     /// their magnitude, than [`Normal`]).
936     ///
937     /// Subnormal numbers are larger in magnitude than [`Zero`] but smaller in magnitude than all
938     /// [`Normal`] numbers.
939     ///
940     /// [`Normal`]: Self::Normal
941     /// [`Zero`]: Self::Zero
942     #[stable(feature = "rust1", since = "1.0.0")]
943     Subnormal,
944
945     /// A regular floating point number, not any of the exceptional categories.
946     ///
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")]
952     Normal,
953 }
954
955 #[doc(hidden)]
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>;
963 }
964
965 macro_rules! from_str_radix_int_impl {
966     ($($t:ty)*) => {$(
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)
972             }
973         }
974     )*}
975 }
976 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
977
978 macro_rules! doit {
979     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
980         #[inline]
981         fn min_value() -> Self { Self::MIN }
982         #[inline]
983         fn max_value() -> Self { Self::MAX }
984         #[inline]
985         fn from_u32(u: u32) -> Self { u as Self }
986         #[inline]
987         fn checked_mul(&self, other: u32) -> Option<Self> {
988             Self::checked_mul(*self, other as Self)
989         }
990         #[inline]
991         fn checked_sub(&self, other: u32) -> Option<Self> {
992             Self::checked_sub(*self, other as Self)
993         }
994         #[inline]
995         fn checked_add(&self, other: u32) -> Option<Self> {
996             Self::checked_add(*self, other as Self)
997         }
998     })*)
999 }
1000 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
1001
1002 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
1003     use self::IntErrorKind::*;
1004     use self::ParseIntError as PIE;
1005
1006     assert!(
1007         (2..=36).contains(&radix),
1008         "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1009         radix
1010     );
1011
1012     if src.is_empty() {
1013         return Err(PIE { kind: Empty });
1014     }
1015
1016     let is_signed_ty = T::from_u32(0) > T::min_value();
1017
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();
1023
1024     let (is_positive, digits) = match src[0] {
1025         b'+' | b'-' if src[1..].is_empty() => {
1026             return Err(PIE { kind: InvalidDigit });
1027         }
1028         b'+' => (true, &src[1..]),
1029         b'-' if is_signed_ty => (false, &src[1..]),
1030         _ => (true, src),
1031     };
1032
1033     let mut result = T::from_u32(0);
1034     if is_positive {
1035         // The number is positive
1036         for &c in digits {
1037             let x = match (c as char).to_digit(radix) {
1038                 Some(x) => x,
1039                 None => return Err(PIE { kind: InvalidDigit }),
1040             };
1041             result = match result.checked_mul(radix) {
1042                 Some(result) => result,
1043                 None => return Err(PIE { kind: PosOverflow }),
1044             };
1045             result = match result.checked_add(x) {
1046                 Some(result) => result,
1047                 None => return Err(PIE { kind: PosOverflow }),
1048             };
1049         }
1050     } else {
1051         // The number is negative
1052         for &c in digits {
1053             let x = match (c as char).to_digit(radix) {
1054                 Some(x) => x,
1055                 None => return Err(PIE { kind: InvalidDigit }),
1056             };
1057             result = match result.checked_mul(radix) {
1058                 Some(result) => result,
1059                 None => return Err(PIE { kind: NegOverflow }),
1060             };
1061             result = match result.checked_sub(x) {
1062                 Some(result) => result,
1063                 None => return Err(PIE { kind: NegOverflow }),
1064             };
1065         }
1066     }
1067     Ok(result)
1068 }