diff options
| author | Matthias Krüger <matthias.krueger@famsik.de> | 2022-02-19 06:45:33 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-02-19 06:45:33 +0100 |
| commit | 5a083dbbe6cbb5e7bcab3b21942d162b4628e76f (patch) | |
| tree | 590c5ad9b11b38712fa88492d17fb1659ef2cdf4 /compiler | |
| parent | c28940e49d31c0abaaec91ff3071932335b5b3b6 (diff) | |
| parent | 8cd9dfad1e2f24e52e022bdad52f23286af8c571 (diff) | |
| download | rust-5a083dbbe6cbb5e7bcab3b21942d162b4628e76f.tar.gz rust-5a083dbbe6cbb5e7bcab3b21942d162b4628e76f.zip | |
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
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), + } } } |
