]> git.lizzy.rs Git - rust.git/blob - library/core/src/num/mod.rs
Auto merge of #88379 - camelid:cleanup-clean, r=jyn514
[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) => {
98         /// Calculates the complete product `self * rhs` without the possibility to overflow.
99         ///
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.
102         ///
103         /// # Examples
104         ///
105         /// Basic usage:
106         ///
107         /// Please note that this example is shared between integer types.
108         /// Which explains why `u32` is used here.
109         ///
110         /// ```
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));
114         /// ```
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"]
119         #[inline]
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)
126         }
127
128         /// Calculates the "full multiplication" `self * rhs + carry`
129         /// without the possibility to overflow.
130         ///
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.
133         ///
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.
137         ///
138         /// # Examples
139         ///
140         /// Basic usage:
141         ///
142         /// Please note that this example is shared between integer types.
143         /// Which explains why `u32` is used here.
144         ///
145         /// ```
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));
151         /// ```
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"]
156         #[inline]
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
161             let wide = unsafe {
162                 (self as $WideT).unchecked_mul(rhs as $WideT).unchecked_add(carry as $WideT)
163             };
164             (wide as $SelfT, (wide >> $BITS) as $SelfT)
165         }
166     };
167 }
168
169 #[lang = "i8"]
170 impl i8 {
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]", "", "" }
174 }
175
176 #[lang = "i16"]
177 impl i16 {
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]", "", "" }
181 }
182
183 #[lang = "i32"]
184 impl i32 {
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]", "", "" }
189 }
190
191 #[lang = "i64"]
192 impl i64 {
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]", "", "" }
198 }
199
200 #[lang = "i128"]
201 impl i128 {
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]", "", "" }
210 }
211
212 #[cfg(target_pointer_width = "16")]
213 #[lang = "isize"]
214 impl isize {
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!() }
219 }
220
221 #[cfg(target_pointer_width = "32")]
222 #[lang = "isize"]
223 impl isize {
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!() }
229 }
230
231 #[cfg(target_pointer_width = "64")]
232 #[lang = "isize"]
233 impl isize {
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!() }
240 }
241
242 /// If 6th bit set ascii is upper case.
243 const ASCII_CASE_MASK: u8 = 0b0010_0000;
244
245 #[lang = "u8"]
246 impl u8 {
247     widening_impl! { u8, u16, 8 }
248     uint_impl! { u8, u8, i8, 8, 255, 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
249     "[0x12]", "", "" }
250
251     /// Checks if the value is within the ASCII range.
252     ///
253     /// # Examples
254     ///
255     /// ```
256     /// let ascii = 97u8;
257     /// let non_ascii = 150u8;
258     ///
259     /// assert!(ascii.is_ascii());
260     /// assert!(!non_ascii.is_ascii());
261     /// ```
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")]
264     #[inline]
265     pub const fn is_ascii(&self) -> bool {
266         *self & 128 == 0
267     }
268
269     /// Makes a copy of the value in its ASCII upper case equivalent.
270     ///
271     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
272     /// but non-ASCII letters are unchanged.
273     ///
274     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
275     ///
276     /// # Examples
277     ///
278     /// ```
279     /// let lowercase_a = 97u8;
280     ///
281     /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
282     /// ```
283     ///
284     /// [`make_ascii_uppercase`]: Self::make_ascii_uppercase
285     #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
286     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
287     #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
288     #[inline]
289     pub const fn to_ascii_uppercase(&self) -> u8 {
290         // Unset the fifth bit if this is a lowercase letter
291         *self & !((self.is_ascii_lowercase() as u8) * ASCII_CASE_MASK)
292     }
293
294     /// Makes a copy of the value in its ASCII lower case equivalent.
295     ///
296     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
297     /// but non-ASCII letters are unchanged.
298     ///
299     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
300     ///
301     /// # Examples
302     ///
303     /// ```
304     /// let uppercase_a = 65u8;
305     ///
306     /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
307     /// ```
308     ///
309     /// [`make_ascii_lowercase`]: Self::make_ascii_lowercase
310     #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
311     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
312     #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
313     #[inline]
314     pub const fn to_ascii_lowercase(&self) -> u8 {
315         // Set the fifth bit if this is an uppercase letter
316         *self | (self.is_ascii_uppercase() as u8 * ASCII_CASE_MASK)
317     }
318
319     /// Assumes self is ascii
320     #[inline]
321     pub(crate) const fn ascii_change_case_unchecked(&self) -> u8 {
322         *self ^ ASCII_CASE_MASK
323     }
324
325     /// Checks that two values are an ASCII case-insensitive match.
326     ///
327     /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
328     ///
329     /// # Examples
330     ///
331     /// ```
332     /// let lowercase_a = 97u8;
333     /// let uppercase_a = 65u8;
334     ///
335     /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
336     /// ```
337     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
338     #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
339     #[inline]
340     pub const fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
341         self.to_ascii_lowercase() == other.to_ascii_lowercase()
342     }
343
344     /// Converts this value to its ASCII upper case equivalent in-place.
345     ///
346     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
347     /// but non-ASCII letters are unchanged.
348     ///
349     /// To return a new uppercased value without modifying the existing one, use
350     /// [`to_ascii_uppercase`].
351     ///
352     /// # Examples
353     ///
354     /// ```
355     /// let mut byte = b'a';
356     ///
357     /// byte.make_ascii_uppercase();
358     ///
359     /// assert_eq!(b'A', byte);
360     /// ```
361     ///
362     /// [`to_ascii_uppercase`]: Self::to_ascii_uppercase
363     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
364     #[inline]
365     pub fn make_ascii_uppercase(&mut self) {
366         *self = self.to_ascii_uppercase();
367     }
368
369     /// Converts this value to its ASCII lower case equivalent in-place.
370     ///
371     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
372     /// but non-ASCII letters are unchanged.
373     ///
374     /// To return a new lowercased value without modifying the existing one, use
375     /// [`to_ascii_lowercase`].
376     ///
377     /// # Examples
378     ///
379     /// ```
380     /// let mut byte = b'A';
381     ///
382     /// byte.make_ascii_lowercase();
383     ///
384     /// assert_eq!(b'a', byte);
385     /// ```
386     ///
387     /// [`to_ascii_lowercase`]: Self::to_ascii_lowercase
388     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
389     #[inline]
390     pub fn make_ascii_lowercase(&mut self) {
391         *self = self.to_ascii_lowercase();
392     }
393
394     /// Checks if the value is an ASCII alphabetic character:
395     ///
396     /// - U+0041 'A' ..= U+005A 'Z', or
397     /// - U+0061 'a' ..= U+007A 'z'.
398     ///
399     /// # Examples
400     ///
401     /// ```
402     /// let uppercase_a = b'A';
403     /// let uppercase_g = b'G';
404     /// let a = b'a';
405     /// let g = b'g';
406     /// let zero = b'0';
407     /// let percent = b'%';
408     /// let space = b' ';
409     /// let lf = b'\n';
410     /// let esc = 0x1b_u8;
411     ///
412     /// assert!(uppercase_a.is_ascii_alphabetic());
413     /// assert!(uppercase_g.is_ascii_alphabetic());
414     /// assert!(a.is_ascii_alphabetic());
415     /// assert!(g.is_ascii_alphabetic());
416     /// assert!(!zero.is_ascii_alphabetic());
417     /// assert!(!percent.is_ascii_alphabetic());
418     /// assert!(!space.is_ascii_alphabetic());
419     /// assert!(!lf.is_ascii_alphabetic());
420     /// assert!(!esc.is_ascii_alphabetic());
421     /// ```
422     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
423     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
424     #[inline]
425     pub const fn is_ascii_alphabetic(&self) -> bool {
426         matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
427     }
428
429     /// Checks if the value is an ASCII uppercase character:
430     /// U+0041 'A' ..= U+005A 'Z'.
431     ///
432     /// # Examples
433     ///
434     /// ```
435     /// let uppercase_a = b'A';
436     /// let uppercase_g = b'G';
437     /// let a = b'a';
438     /// let g = b'g';
439     /// let zero = b'0';
440     /// let percent = b'%';
441     /// let space = b' ';
442     /// let lf = b'\n';
443     /// let esc = 0x1b_u8;
444     ///
445     /// assert!(uppercase_a.is_ascii_uppercase());
446     /// assert!(uppercase_g.is_ascii_uppercase());
447     /// assert!(!a.is_ascii_uppercase());
448     /// assert!(!g.is_ascii_uppercase());
449     /// assert!(!zero.is_ascii_uppercase());
450     /// assert!(!percent.is_ascii_uppercase());
451     /// assert!(!space.is_ascii_uppercase());
452     /// assert!(!lf.is_ascii_uppercase());
453     /// assert!(!esc.is_ascii_uppercase());
454     /// ```
455     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
456     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
457     #[inline]
458     pub const fn is_ascii_uppercase(&self) -> bool {
459         matches!(*self, b'A'..=b'Z')
460     }
461
462     /// Checks if the value is an ASCII lowercase character:
463     /// U+0061 'a' ..= U+007A 'z'.
464     ///
465     /// # Examples
466     ///
467     /// ```
468     /// let uppercase_a = b'A';
469     /// let uppercase_g = b'G';
470     /// let a = b'a';
471     /// let g = b'g';
472     /// let zero = b'0';
473     /// let percent = b'%';
474     /// let space = b' ';
475     /// let lf = b'\n';
476     /// let esc = 0x1b_u8;
477     ///
478     /// assert!(!uppercase_a.is_ascii_lowercase());
479     /// assert!(!uppercase_g.is_ascii_lowercase());
480     /// assert!(a.is_ascii_lowercase());
481     /// assert!(g.is_ascii_lowercase());
482     /// assert!(!zero.is_ascii_lowercase());
483     /// assert!(!percent.is_ascii_lowercase());
484     /// assert!(!space.is_ascii_lowercase());
485     /// assert!(!lf.is_ascii_lowercase());
486     /// assert!(!esc.is_ascii_lowercase());
487     /// ```
488     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
489     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
490     #[inline]
491     pub const fn is_ascii_lowercase(&self) -> bool {
492         matches!(*self, b'a'..=b'z')
493     }
494
495     /// Checks if the value is an ASCII alphanumeric character:
496     ///
497     /// - U+0041 'A' ..= U+005A 'Z', or
498     /// - U+0061 'a' ..= U+007A 'z', or
499     /// - U+0030 '0' ..= U+0039 '9'.
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_alphanumeric());
515     /// assert!(uppercase_g.is_ascii_alphanumeric());
516     /// assert!(a.is_ascii_alphanumeric());
517     /// assert!(g.is_ascii_alphanumeric());
518     /// assert!(zero.is_ascii_alphanumeric());
519     /// assert!(!percent.is_ascii_alphanumeric());
520     /// assert!(!space.is_ascii_alphanumeric());
521     /// assert!(!lf.is_ascii_alphanumeric());
522     /// assert!(!esc.is_ascii_alphanumeric());
523     /// ```
524     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
525     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
526     #[inline]
527     pub const fn is_ascii_alphanumeric(&self) -> bool {
528         matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
529     }
530
531     /// Checks if the value is an ASCII decimal digit:
532     /// U+0030 '0' ..= U+0039 '9'.
533     ///
534     /// # Examples
535     ///
536     /// ```
537     /// let uppercase_a = b'A';
538     /// let uppercase_g = b'G';
539     /// let a = b'a';
540     /// let g = b'g';
541     /// let zero = b'0';
542     /// let percent = b'%';
543     /// let space = b' ';
544     /// let lf = b'\n';
545     /// let esc = 0x1b_u8;
546     ///
547     /// assert!(!uppercase_a.is_ascii_digit());
548     /// assert!(!uppercase_g.is_ascii_digit());
549     /// assert!(!a.is_ascii_digit());
550     /// assert!(!g.is_ascii_digit());
551     /// assert!(zero.is_ascii_digit());
552     /// assert!(!percent.is_ascii_digit());
553     /// assert!(!space.is_ascii_digit());
554     /// assert!(!lf.is_ascii_digit());
555     /// assert!(!esc.is_ascii_digit());
556     /// ```
557     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
558     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
559     #[inline]
560     pub const fn is_ascii_digit(&self) -> bool {
561         matches!(*self, b'0'..=b'9')
562     }
563
564     /// Checks if the value is an ASCII hexadecimal digit:
565     ///
566     /// - U+0030 '0' ..= U+0039 '9', or
567     /// - U+0041 'A' ..= U+0046 'F', or
568     /// - U+0061 'a' ..= U+0066 'f'.
569     ///
570     /// # Examples
571     ///
572     /// ```
573     /// let uppercase_a = b'A';
574     /// let uppercase_g = b'G';
575     /// let a = b'a';
576     /// let g = b'g';
577     /// let zero = b'0';
578     /// let percent = b'%';
579     /// let space = b' ';
580     /// let lf = b'\n';
581     /// let esc = 0x1b_u8;
582     ///
583     /// assert!(uppercase_a.is_ascii_hexdigit());
584     /// assert!(!uppercase_g.is_ascii_hexdigit());
585     /// assert!(a.is_ascii_hexdigit());
586     /// assert!(!g.is_ascii_hexdigit());
587     /// assert!(zero.is_ascii_hexdigit());
588     /// assert!(!percent.is_ascii_hexdigit());
589     /// assert!(!space.is_ascii_hexdigit());
590     /// assert!(!lf.is_ascii_hexdigit());
591     /// assert!(!esc.is_ascii_hexdigit());
592     /// ```
593     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
594     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
595     #[inline]
596     pub const fn is_ascii_hexdigit(&self) -> bool {
597         matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
598     }
599
600     /// Checks if the value is an ASCII punctuation character:
601     ///
602     /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
603     /// - U+003A ..= U+0040 `: ; < = > ? @`, or
604     /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
605     /// - U+007B ..= U+007E `{ | } ~`
606     ///
607     /// # Examples
608     ///
609     /// ```
610     /// let uppercase_a = b'A';
611     /// let uppercase_g = b'G';
612     /// let a = b'a';
613     /// let g = b'g';
614     /// let zero = b'0';
615     /// let percent = b'%';
616     /// let space = b' ';
617     /// let lf = b'\n';
618     /// let esc = 0x1b_u8;
619     ///
620     /// assert!(!uppercase_a.is_ascii_punctuation());
621     /// assert!(!uppercase_g.is_ascii_punctuation());
622     /// assert!(!a.is_ascii_punctuation());
623     /// assert!(!g.is_ascii_punctuation());
624     /// assert!(!zero.is_ascii_punctuation());
625     /// assert!(percent.is_ascii_punctuation());
626     /// assert!(!space.is_ascii_punctuation());
627     /// assert!(!lf.is_ascii_punctuation());
628     /// assert!(!esc.is_ascii_punctuation());
629     /// ```
630     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
631     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
632     #[inline]
633     pub const fn is_ascii_punctuation(&self) -> bool {
634         matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
635     }
636
637     /// Checks if the value is an ASCII graphic character:
638     /// U+0021 '!' ..= U+007E '~'.
639     ///
640     /// # Examples
641     ///
642     /// ```
643     /// let uppercase_a = b'A';
644     /// let uppercase_g = b'G';
645     /// let a = b'a';
646     /// let g = b'g';
647     /// let zero = b'0';
648     /// let percent = b'%';
649     /// let space = b' ';
650     /// let lf = b'\n';
651     /// let esc = 0x1b_u8;
652     ///
653     /// assert!(uppercase_a.is_ascii_graphic());
654     /// assert!(uppercase_g.is_ascii_graphic());
655     /// assert!(a.is_ascii_graphic());
656     /// assert!(g.is_ascii_graphic());
657     /// assert!(zero.is_ascii_graphic());
658     /// assert!(percent.is_ascii_graphic());
659     /// assert!(!space.is_ascii_graphic());
660     /// assert!(!lf.is_ascii_graphic());
661     /// assert!(!esc.is_ascii_graphic());
662     /// ```
663     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
664     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
665     #[inline]
666     pub const fn is_ascii_graphic(&self) -> bool {
667         matches!(*self, b'!'..=b'~')
668     }
669
670     /// Checks if the value is an ASCII whitespace character:
671     /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
672     /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
673     ///
674     /// Rust uses the WhatWG Infra Standard's [definition of ASCII
675     /// whitespace][infra-aw]. There are several other definitions in
676     /// wide use. For instance, [the POSIX locale][pct] includes
677     /// U+000B VERTICAL TAB as well as all the above characters,
678     /// but—from the very same specification—[the default rule for
679     /// "field splitting" in the Bourne shell][bfs] considers *only*
680     /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
681     ///
682     /// If you are writing a program that will process an existing
683     /// file format, check what that format's definition of whitespace is
684     /// before using this function.
685     ///
686     /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
687     /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
688     /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
689     ///
690     /// # Examples
691     ///
692     /// ```
693     /// let uppercase_a = b'A';
694     /// let uppercase_g = b'G';
695     /// let a = b'a';
696     /// let g = b'g';
697     /// let zero = b'0';
698     /// let percent = b'%';
699     /// let space = b' ';
700     /// let lf = b'\n';
701     /// let esc = 0x1b_u8;
702     ///
703     /// assert!(!uppercase_a.is_ascii_whitespace());
704     /// assert!(!uppercase_g.is_ascii_whitespace());
705     /// assert!(!a.is_ascii_whitespace());
706     /// assert!(!g.is_ascii_whitespace());
707     /// assert!(!zero.is_ascii_whitespace());
708     /// assert!(!percent.is_ascii_whitespace());
709     /// assert!(space.is_ascii_whitespace());
710     /// assert!(lf.is_ascii_whitespace());
711     /// assert!(!esc.is_ascii_whitespace());
712     /// ```
713     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
714     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
715     #[inline]
716     pub const fn is_ascii_whitespace(&self) -> bool {
717         matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
718     }
719
720     /// Checks if the value is an ASCII control character:
721     /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
722     /// Note that most ASCII whitespace characters are control
723     /// characters, but SPACE is not.
724     ///
725     /// # Examples
726     ///
727     /// ```
728     /// let uppercase_a = b'A';
729     /// let uppercase_g = b'G';
730     /// let a = b'a';
731     /// let g = b'g';
732     /// let zero = b'0';
733     /// let percent = b'%';
734     /// let space = b' ';
735     /// let lf = b'\n';
736     /// let esc = 0x1b_u8;
737     ///
738     /// assert!(!uppercase_a.is_ascii_control());
739     /// assert!(!uppercase_g.is_ascii_control());
740     /// assert!(!a.is_ascii_control());
741     /// assert!(!g.is_ascii_control());
742     /// assert!(!zero.is_ascii_control());
743     /// assert!(!percent.is_ascii_control());
744     /// assert!(!space.is_ascii_control());
745     /// assert!(lf.is_ascii_control());
746     /// assert!(esc.is_ascii_control());
747     /// ```
748     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
749     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
750     #[inline]
751     pub const fn is_ascii_control(&self) -> bool {
752         matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
753     }
754
755     /// Returns an iterator that produces an escaped version of a `u8`,
756     /// treating it as an ASCII character.
757     ///
758     /// The behavior is identical to [`ascii::escape_default`].
759     ///
760     /// # Examples
761     ///
762     /// ```
763     /// #![feature(inherent_ascii_escape)]
764     ///
765     /// assert_eq!("0", b'0'.escape_ascii().to_string());
766     /// assert_eq!("\\t", b'\t'.escape_ascii().to_string());
767     /// assert_eq!("\\r", b'\r'.escape_ascii().to_string());
768     /// assert_eq!("\\n", b'\n'.escape_ascii().to_string());
769     /// assert_eq!("\\'", b'\''.escape_ascii().to_string());
770     /// assert_eq!("\\\"", b'"'.escape_ascii().to_string());
771     /// assert_eq!("\\\\", b'\\'.escape_ascii().to_string());
772     /// assert_eq!("\\x9d", b'\x9d'.escape_ascii().to_string());
773     /// ```
774     #[must_use = "this returns the escaped byte as an iterator, \
775                   without modifying the original"]
776     #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
777     #[inline]
778     pub fn escape_ascii(&self) -> ascii::EscapeDefault {
779         ascii::escape_default(*self)
780     }
781 }
782
783 #[lang = "u16"]
784 impl u16 {
785     widening_impl! { u16, u32, 16 }
786     uint_impl! { u16, u16, i16, 16, 65535, 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
787     "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
788 }
789
790 #[lang = "u32"]
791 impl u32 {
792     widening_impl! { u32, u64, 32 }
793     uint_impl! { u32, u32, i32, 32, 4294967295, 8, "0x10000b3", "0xb301", "0x12345678",
794     "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
795 }
796
797 #[lang = "u64"]
798 impl u64 {
799     widening_impl! { u64, u128, 64 }
800     uint_impl! { u64, u64, i64, 64, 18446744073709551615, 12, "0xaa00000000006e1", "0x6e10aa",
801     "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
802     "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
803     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
804     "", ""}
805 }
806
807 #[lang = "u128"]
808 impl u128 {
809     uint_impl! { u128, u128, i128, 128, 340282366920938463463374607431768211455, 16,
810     "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
811     "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
812     "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
813       0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
814     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
815       0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
816      "", ""}
817 }
818
819 #[cfg(target_pointer_width = "16")]
820 #[lang = "usize"]
821 impl usize {
822     widening_impl! { usize, u32, 16 }
823     uint_impl! { usize, u16, isize, 16, 65535, 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
824     "[0x34, 0x12]", "[0x12, 0x34]",
825     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
826 }
827 #[cfg(target_pointer_width = "32")]
828 #[lang = "usize"]
829 impl usize {
830     widening_impl! { usize, u64, 32 }
831     uint_impl! { usize, u32, isize, 32, 4294967295, 8, "0x10000b3", "0xb301", "0x12345678",
832     "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
833     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
834 }
835
836 #[cfg(target_pointer_width = "64")]
837 #[lang = "usize"]
838 impl usize {
839     widening_impl! { usize, u128, 64 }
840     uint_impl! { usize, u64, isize, 64, 18446744073709551615, 12, "0xaa00000000006e1", "0x6e10aa",
841     "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
842     "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
843      "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
844     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
845 }
846
847 /// A classification of floating point numbers.
848 ///
849 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
850 /// their documentation for more.
851 ///
852 /// # Examples
853 ///
854 /// ```
855 /// use std::num::FpCategory;
856 ///
857 /// let num = 12.4_f32;
858 /// let inf = f32::INFINITY;
859 /// let zero = 0f32;
860 /// let sub: f32 = 1.1754942e-38;
861 /// let nan = f32::NAN;
862 ///
863 /// assert_eq!(num.classify(), FpCategory::Normal);
864 /// assert_eq!(inf.classify(), FpCategory::Infinite);
865 /// assert_eq!(zero.classify(), FpCategory::Zero);
866 /// assert_eq!(nan.classify(), FpCategory::Nan);
867 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
868 /// ```
869 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
870 #[stable(feature = "rust1", since = "1.0.0")]
871 pub enum FpCategory {
872     /// NaN (not a number): this value results from calculations like `(-1.0).sqrt()`.
873     ///
874     /// See [the documentation for `f32`](f32) for more information on the unusual properties
875     /// of NaN.
876     #[stable(feature = "rust1", since = "1.0.0")]
877     Nan,
878
879     /// Positive or negative infinity, which often results from dividing a nonzero number
880     /// by zero.
881     #[stable(feature = "rust1", since = "1.0.0")]
882     Infinite,
883
884     /// Positive or negative zero.
885     ///
886     /// See [the documentation for `f32`](f32) for more information on the signedness of zeroes.
887     #[stable(feature = "rust1", since = "1.0.0")]
888     Zero,
889
890     /// “Subnormal” or “denormal” floating point representation (less precise, relative to
891     /// their magnitude, than [`Normal`]).
892     ///
893     /// Subnormal numbers are larger in magnitude than [`Zero`] but smaller in magnitude than all
894     /// [`Normal`] numbers.
895     ///
896     /// [`Normal`]: Self::Normal
897     /// [`Zero`]: Self::Zero
898     #[stable(feature = "rust1", since = "1.0.0")]
899     Subnormal,
900
901     /// A regular floating point number, not any of the exceptional categories.
902     ///
903     /// The smallest positive normal numbers are [`f32::MIN_POSITIVE`] and [`f64::MIN_POSITIVE`],
904     /// and the largest positive normal numbers are [`f32::MAX`] and [`f64::MAX`]. (Unlike signed
905     /// integers, floating point numbers are symmetric in their range, so negating any of these
906     /// constants will produce their negative counterpart.)
907     #[stable(feature = "rust1", since = "1.0.0")]
908     Normal,
909 }
910
911 #[doc(hidden)]
912 trait FromStrRadixHelper: PartialOrd + Copy {
913     fn min_value() -> Self;
914     fn max_value() -> Self;
915     fn from_u32(u: u32) -> Self;
916     fn checked_mul(&self, other: u32) -> Option<Self>;
917     fn checked_sub(&self, other: u32) -> Option<Self>;
918     fn checked_add(&self, other: u32) -> Option<Self>;
919 }
920
921 macro_rules! from_str_radix_int_impl {
922     ($($t:ty)*) => {$(
923         #[stable(feature = "rust1", since = "1.0.0")]
924         impl FromStr for $t {
925             type Err = ParseIntError;
926             fn from_str(src: &str) -> Result<Self, ParseIntError> {
927                 from_str_radix(src, 10)
928             }
929         }
930     )*}
931 }
932 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
933
934 macro_rules! doit {
935     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
936         #[inline]
937         fn min_value() -> Self { Self::MIN }
938         #[inline]
939         fn max_value() -> Self { Self::MAX }
940         #[inline]
941         fn from_u32(u: u32) -> Self { u as Self }
942         #[inline]
943         fn checked_mul(&self, other: u32) -> Option<Self> {
944             Self::checked_mul(*self, other as Self)
945         }
946         #[inline]
947         fn checked_sub(&self, other: u32) -> Option<Self> {
948             Self::checked_sub(*self, other as Self)
949         }
950         #[inline]
951         fn checked_add(&self, other: u32) -> Option<Self> {
952             Self::checked_add(*self, other as Self)
953         }
954     })*)
955 }
956 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
957
958 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
959     use self::IntErrorKind::*;
960     use self::ParseIntError as PIE;
961
962     assert!(
963         (2..=36).contains(&radix),
964         "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
965         radix
966     );
967
968     if src.is_empty() {
969         return Err(PIE { kind: Empty });
970     }
971
972     let is_signed_ty = T::from_u32(0) > T::min_value();
973
974     // all valid digits are ascii, so we will just iterate over the utf8 bytes
975     // and cast them to chars. .to_digit() will safely return None for anything
976     // other than a valid ascii digit for the given radix, including the first-byte
977     // of multi-byte sequences
978     let src = src.as_bytes();
979
980     let (is_positive, digits) = match src[0] {
981         b'+' | b'-' if src[1..].is_empty() => {
982             return Err(PIE { kind: InvalidDigit });
983         }
984         b'+' => (true, &src[1..]),
985         b'-' if is_signed_ty => (false, &src[1..]),
986         _ => (true, src),
987     };
988
989     let mut result = T::from_u32(0);
990     if is_positive {
991         // The number is positive
992         for &c in digits {
993             let x = match (c as char).to_digit(radix) {
994                 Some(x) => x,
995                 None => return Err(PIE { kind: InvalidDigit }),
996             };
997             result = match result.checked_mul(radix) {
998                 Some(result) => result,
999                 None => return Err(PIE { kind: PosOverflow }),
1000             };
1001             result = match result.checked_add(x) {
1002                 Some(result) => result,
1003                 None => return Err(PIE { kind: PosOverflow }),
1004             };
1005         }
1006     } else {
1007         // The number is negative
1008         for &c in digits {
1009             let x = match (c as char).to_digit(radix) {
1010                 Some(x) => x,
1011                 None => return Err(PIE { kind: InvalidDigit }),
1012             };
1013             result = match result.checked_mul(radix) {
1014                 Some(result) => result,
1015                 None => return Err(PIE { kind: NegOverflow }),
1016             };
1017             result = match result.checked_sub(x) {
1018                 Some(result) => result,
1019                 None => return Err(PIE { kind: NegOverflow }),
1020             };
1021         }
1022     }
1023     Ok(result)
1024 }