Fix ScalarInt to char conversion
to avoid panic for invalid Unicode scalar values
This commit is contained in:
@@ -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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user