We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent b3ac526 commit 9c3d81eCopy full SHA for 9c3d81e
library/core/src/char/methods.rs
@@ -1,6 +1,5 @@
1
//! impl char {}
2
3
-use crate::intrinsics::likely;
4
use crate::slice;
5
use crate::str::from_utf8_unchecked_mut;
6
use crate::unicode::printable::is_printable;
@@ -332,21 +331,16 @@ impl char {
332
331
#[inline]
333
pub fn to_digit(self, radix: u32) -> Option<u32> {
334
assert!(radix <= 36, "to_digit: radix is too high (maximum 36)");
335
- // the code is split up here to improve execution speed for cases where
336
- // the `radix` is constant and 10 or smaller
337
- let val = if likely(radix <= 10) {
338
- // If not a digit, a number greater than radix will be created.
339
- (self as u32).wrapping_sub('0' as u32)
340
- } else {
341
- match self {
342
- '0'..='9' => self as u32 - '0' as u32,
343
- 'a'..='z' => self as u32 - 'a' as u32 + 10,
344
- 'A'..='Z' => self as u32 - 'A' as u32 + 10,
345
- _ => return None,
+ // If not a digit, a number greater than radix will be created.
+ let mut digit = (self as u32).wrapping_sub('0' as u32);
+ if radix > 10 {
+ if digit < 10 {
+ return Some(digit);
346
}
347
- };
348
-
349
- if val < radix { Some(val) } else { None }
+ // Force the 6th bit to be set to ensure ascii is lower case.
+ digit = (self as u32 | 0b10_0000).wrapping_sub('a' as u32).saturating_add(10);
+ }
+ (digit < radix).then_some(digit)
350
351
352
/// Returns an iterator that yields the hexadecimal Unicode escape of a
library/core/src/lib.rs
@@ -66,6 +66,7 @@
66
#![feature(allow_internal_unstable)]
67
#![feature(arbitrary_self_types)]
68
#![feature(asm)]
69
+#![feature(bool_to_option)]
70
#![feature(cfg_target_has_atomic)]
71
#![feature(const_heap)]
72
#![feature(const_alloc_layout)]
library/core/tests/char.rs
@@ -67,10 +67,20 @@ fn test_to_digit() {
assert_eq!('A'.to_digit(16), Some(10));
assert_eq!('b'.to_digit(16), Some(11));
assert_eq!('B'.to_digit(16), Some(11));
+ assert_eq!('A'.to_digit(36), Some(10));
assert_eq!('z'.to_digit(36), Some(35));
assert_eq!('Z'.to_digit(36), Some(35));
- assert_eq!(' '.to_digit(10), None);
73
+ assert_eq!('['.to_digit(36), None);
74
+ assert_eq!('`'.to_digit(36), None);
75
+ assert_eq!('{'.to_digit(36), None);
76
assert_eq!('$'.to_digit(36), None);
77
+ assert_eq!('@'.to_digit(16), None);
78
+ assert_eq!('G'.to_digit(16), None);
79
+ assert_eq!('g'.to_digit(16), None);
80
+ assert_eq!(' '.to_digit(10), None);
81
+ assert_eq!('/'.to_digit(10), None);
82
+ assert_eq!(':'.to_digit(10), None);
83
+ assert_eq!(':'.to_digit(11), None);
84
85
86
#[test]
0 commit comments