Skip to content

Commit

Permalink
Simpler way to convert to digit
Browse files Browse the repository at this point in the history
  • Loading branch information
gilescope committed Feb 14, 2021
1 parent b70428b commit 845c14d
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions library/core/src/char/methods.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit 845c14d

Please sign in to comment.