1
Fork 0

Rollup merge of #94086 - tmiasko:char-try-from-scalar-int, r=davidtwco

Fix ScalarInt to char conversion

to avoid panic for invalid Unicode scalar values
This commit is contained in:
Matthias Krüger 2022-02-19 06:45:33 +01:00 committed by GitHub
commit 5a083dbbe6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
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),
}
}
}