diff options
| author | Tomasz Miąsko <tomasz.miasko@gmail.com> | 2022-02-17 00:00:00 +0000 |
|---|---|---|
| committer | Tomasz Miąsko <tomasz.miasko@gmail.com> | 2022-02-17 16:50:31 +0100 |
| commit | 8cd9dfad1e2f24e52e022bdad52f23286af8c571 (patch) | |
| tree | 6f5ed9924e8bd89fd85ab818f2dd03facadc0a54 /compiler | |
| parent | 30b3f35c420694a4f24e5a4df00f06073f4f3a37 (diff) | |
| download | rust-8cd9dfad1e2f24e52e022bdad52f23286af8c571.tar.gz rust-8cd9dfad1e2f24e52e022bdad52f23286af8c571.zip | |
Fix ScalarInt to char conversion
to avoid panic for invalid Unicode scalar values
Diffstat (limited to 'compiler')
| -rw-r--r-- | compiler/rustc_middle/src/ty/consts/int.rs | 18 |
1 files changed, 14 insertions, 4 deletions
diff --git a/compiler/rustc_middle/src/ty/consts/int.rs b/compiler/rustc_middle/src/ty/consts/int.rs index de45e1bb851..ca1db2fd551 100644 --- a/compiler/rustc_middle/src/ty/consts/int.rs +++ b/compiler/rustc_middle/src/ty/consts/int.rs @@ -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), + } } } |
