@@ -118,6 +118,26 @@ pub pure fn is_digit(c: char) -> bool {
118
118
unicode:: general_category:: No ( c) ;
119
119
}
120
120
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
+
121
141
/**
122
142
* Convert a char to the corresponding digit.
123
143
*
@@ -127,9 +147,15 @@ pub pure fn is_digit(c: char) -> bool {
127
147
* between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
128
148
* 'b' or 'B', 11, etc. Returns none if the char does not
129
149
* refer to a digit in the given radix.
150
+ *
151
+ * # Failure
152
+ * Fails if given a `radix` outside the range `[0..36]`.
130
153
*/
131
154
#[ inline]
132
155
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
+ }
133
159
let val = match c {
134
160
'0' .. '9' => c as uint - ( '0' as uint ) ,
135
161
'a' .. 'z' => c as uint + 10 u - ( 'a' as uint ) ,
@@ -140,6 +166,30 @@ pub pure fn to_digit(c: char, radix: uint) -> Option<uint> {
140
166
else { None }
141
167
}
142
168
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 - 10 u) as char )
187
+ }
188
+ } else {
189
+ None
190
+ }
191
+ }
192
+
143
193
/**
144
194
* Return the hexadecimal unicode escape of a char.
145
195
*
0 commit comments