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:
commit
5a083dbbe6
3 changed files with 52 additions and 22 deletions
|
@ -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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue