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