diff options
| author | Giles Cope <gilescope@gmail.com> | 2021-02-14 11:34:22 +0000 |
|---|---|---|
| committer | Giles Cope <gilescope@gmail.com> | 2021-02-14 17:06:16 +0000 |
| commit | 845c14db05bb19bb7c8a0df835a9951073d313bb (patch) | |
| tree | de9c2ac8e50a6f078d3b8e52854c52f444fc7520 | |
| parent | b70428b9fb08ce79ebc28c3f2c07819bba1a467d (diff) | |
| download | rust-845c14db05bb19bb7c8a0df835a9951073d313bb.tar.gz rust-845c14db05bb19bb7c8a0df835a9951073d313bb.zip | |
Simpler way to convert to digit
| -rw-r--r-- | library/core/src/char/methods.rs | 13 |
1 files changed, 6 insertions, 7 deletions
diff --git a/library/core/src/char/methods.rs b/library/core/src/char/methods.rs index e450240527a..d92df5532e5 100644 --- a/library/core/src/char/methods.rs +++ b/library/core/src/char/methods.rs @@ -1,5 +1,6 @@ //! impl char {} +use crate::intrinsics::likely; use crate::slice; use crate::str::from_utf8_unchecked_mut; use crate::unicode::printable::is_printable; @@ -330,16 +331,14 @@ impl char { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_digit(self, radix: u32) -> Option<u32> { + assert!(radix <= 36, "to_digit: radix is too high (maximum 36)"); + const ASCII_DIGIT_MASK: u32 = 0b11_0000; // the code is split up here to improve execution speed for cases where // the `radix` is constant and 10 or smaller - let val = if radix <= 10 { - match self { - '0'..='9' => self as u32 - '0' as u32, - _ => return None, - } + let val = if likely(radix <= 10) { + // If not a digit, a number greater than radix will be created. + self as u32 ^ ASCII_DIGIT_MASK } else { - assert!(radix <= 36, "to_digit: radix is too high (maximum 36)"); - match self { '0'..='9' => self as u32 - '0' as u32, 'a'..='z' => self as u32 - 'a' as u32 + 10, |
