Fix ScalarInt to char conversion

to avoid panic for invalid Unicode scalar values
This commit is contained in:
Tomasz Miąsko
2022-02-17 00:00:00 +00:00
parent 30b3f35c42
commit 8cd9dfad1e
3 changed files with 52 additions and 22 deletions

View File

@@ -294,12 +294,22 @@ impl From<char> for ScalarInt {
}
}
/// Error returned when a conversion from ScalarInt to char fails.
#[derive(Debug)]
pub struct CharTryFromScalarInt;
impl TryFrom<ScalarInt> for char {
type Error = Size;
type Error = CharTryFromScalarInt;
#[inline]
fn try_from(int: ScalarInt) -> Result<Self, Size> {
int.to_bits(Size::from_bytes(std::mem::size_of::<char>()))
.map(|u| char::from_u32(u.try_into().unwrap()).unwrap())
fn try_from(int: ScalarInt) -> Result<Self, Self::Error> {
let Ok(bits) = int.to_bits(Size::from_bytes(std::mem::size_of::<char>())) else {
return Err(CharTryFromScalarInt);
};
match char::from_u32(bits.try_into().unwrap()) {
Some(c) => Ok(c),
None => Err(CharTryFromScalarInt),
}
}
}