Skip to content

Commit 05d8301

Browse files
Kimundibrson
authored andcommitted
Added char::from_digit(), char::is_digit_radix() and an argument check to char::to_digit().
1 parent d13b23f commit 05d8301

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/libcore/char.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,26 @@ pub pure fn is_digit(c: char) -> bool {
118118
unicode::general_category::No(c);
119119
}
120120

121+
/**
122+
* Checks if a character parses as a numeric digit in the given radix.
123+
* Compared to `is_digit()`, this function only recognizes the ascii
124+
* characters `0-9`, `a-z` and `A-Z`.
125+
*
126+
* Returns `true` if `c` is a valid digit under `radix`, and `false`
127+
* otherwise.
128+
*
129+
* Fails if given a `radix` > 36.
130+
*
131+
* Note: This just wraps `to_digit()`.
132+
*/
133+
#[inline(always)]
134+
pub pure fn is_digit_radix(c: char, radix: uint) -> bool {
135+
match to_digit(c, radix) {
136+
Some(_) => true,
137+
None => false
138+
}
139+
}
140+
121141
/**
122142
* Convert a char to the corresponding digit.
123143
*
@@ -127,9 +147,15 @@ pub pure fn is_digit(c: char) -> bool {
127147
* between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
128148
* 'b' or 'B', 11, etc. Returns none if the char does not
129149
* refer to a digit in the given radix.
150+
*
151+
* # Failure
152+
* Fails if given a `radix` outside the range `[0..36]`.
130153
*/
131154
#[inline]
132155
pub pure fn to_digit(c: char, radix: uint) -> Option<uint> {
156+
if radix > 36 {
157+
fail fmt!("to_digit: radix %? is to high (maximum 36)", radix)
158+
}
133159
let val = match c {
134160
'0' .. '9' => c as uint - ('0' as uint),
135161
'a' .. 'z' => c as uint + 10u - ('a' as uint),
@@ -140,6 +166,30 @@ pub pure fn to_digit(c: char, radix: uint) -> Option<uint> {
140166
else { None }
141167
}
142168

169+
/**
170+
* Converts a number to the ascii character representing it.
171+
*
172+
* Returns `Some(char)` if `num` represents one digit under `radix`,
173+
* using one character of `0-9` or `a-z`, or `None` if it doesn't.
174+
*
175+
* Fails if given an `radix` > 36.
176+
*/
177+
#[inline]
178+
pub pure fn from_digit(num: uint, radix: uint) -> Option<char> {
179+
if radix > 36 {
180+
fail fmt!("from_digit: radix %? is to high (maximum 36)", num)
181+
}
182+
if num < radix {
183+
if num < 10 {
184+
Some(('0' as uint + num) as char)
185+
} else {
186+
Some(('a' as uint + num - 10u) as char)
187+
}
188+
} else {
189+
None
190+
}
191+
}
192+
143193
/**
144194
* Return the hexadecimal unicode escape of a char.
145195
*

0 commit comments

Comments
 (0)