The panics in from_digit
and to_digit
are rather arbitrary:
pub fn from_digit(num: u32, radix: u32) -> Option<char> {
if radix > 36 {
panic!("from_digit: radix is too high (maximum 36)");
}
if num < radix {
let num = num as u8;
if num < 10 {
Some((b'0' + num) as char)
} else {
Some((b'a' + num - 10) as char)
}
} else {
None
}
}
...
fn to_digit(self, radix: u32) -> Option<u32> {
if radix > 36 {
panic!("to_digit: radix is too high (maximum 36)");
}
let val = match self {
'0' ... '9' => self as u32 - '0' as u32,
'a' ... 'z' => self as u32 - 'a' as u32 + 10,
'A' ... 'Z' => self as u32 - 'A' as u32 + 10,
_ => return None,
};
if val < radix { Some(val) }
else { None }
}
Both functions already return a None
when the number above the radix, and should also return None
rather than crashing the program when the radix is greater than 36. If a crash is still desired, the Option<char>
can simply be unwrapped.
This change is very simple to make. Although both functions are stable, this panic is not encoded in their signatures, and nothing in the standard library relies on this hidden panic; in fact from_digit
is always unwrap
d, while to_digit
is either unwrapped or matched a way compatible with the elimination of this panic (though an error message may need to be tweaked). A cursory search of GitHub suggests this is in fact the case everywhere else, with every invocation I could find either passing 2, 10, 16, or 36 as the radix, unwrapping the result, or manually checking whether the radix was greater than 36 and explicitly panicking if so.
I’m not sure what the timeline is for deprecating semantics, even those that don’t break compilation, but I imagine this would take another release cycle.
Since libcore is being stabilized right now, I’d offer that panicking in the core library should be minimized, since every possible panic reduces Rust’s applicability and usefulness to baremetal systems where safety is a concern.