Skip to content

Commit 845c14d

Browse files
committed
Simpler way to convert to digit
1 parent b70428b commit 845c14d

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

library/core/src/char/methods.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! impl char {}
22
3+
use crate::intrinsics::likely;
34
use crate::slice;
45
use crate::str::from_utf8_unchecked_mut;
56
use crate::unicode::printable::is_printable;
@@ -330,16 +331,14 @@ impl char {
330331
#[stable(feature = "rust1", since = "1.0.0")]
331332
#[inline]
332333
pub fn to_digit(self, radix: u32) -> Option<u32> {
334+
assert!(radix <= 36, "to_digit: radix is too high (maximum 36)");
335+
const ASCII_DIGIT_MASK: u32 = 0b11_0000;
333336
// the code is split up here to improve execution speed for cases where
334337
// the `radix` is constant and 10 or smaller
335-
let val = if radix <= 10 {
336-
match self {
337-
'0'..='9' => self as u32 - '0' as u32,
338-
_ => return None,
339-
}
338+
let val = if likely(radix <= 10) {
339+
// If not a digit, a number greater than radix will be created.
340+
self as u32 ^ ASCII_DIGIT_MASK
340341
} else {
341-
assert!(radix <= 36, "to_digit: radix is too high (maximum 36)");
342-
343342
match self {
344343
'0'..='9' => self as u32 - '0' as u32,
345344
'a'..='z' => self as u32 - 'a' as u32 + 10,

0 commit comments

Comments
 (0)