From ec1775d85d3e65945f5949f1b0e62cad37fe8e7a Mon Sep 17 00:00:00 2001 From: Markus Reiter Date: Wed, 8 May 2024 21:51:50 +0200 Subject: [PATCH] Allow optimizing `u32::from::`. --- library/core/src/char/convert.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/library/core/src/char/convert.rs b/library/core/src/char/convert.rs index f0c2636307fcf..5be203296360a 100644 --- a/library/core/src/char/convert.rs +++ b/library/core/src/char/convert.rs @@ -48,7 +48,12 @@ impl From for u32 { /// ``` #[inline] fn from(c: char) -> Self { - c as u32 + let c = c as Self; + + // SAFETY: `char::MAX` is the highest valid Unicode code point. + unsafe { core::hint::assert_unchecked(c <= char::MAX as Self) }; + + c } } @@ -69,7 +74,12 @@ impl From for u64 { fn from(c: char) -> Self { // The char is casted to the value of the code point, then zero-extended to 64 bit. // See [https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics] - c as u64 + let c = c as Self; + + // SAFETY: `char::MAX` is the highest valid Unicode code point. + unsafe { core::hint::assert_unchecked(c <= char::MAX as Self) }; + + c } } @@ -90,7 +100,12 @@ impl From for u128 { fn from(c: char) -> Self { // The char is casted to the value of the code point, then zero-extended to 128 bit. // See [https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics] - c as u128 + let c = c as Self; + + // SAFETY: `char::MAX` is the highest valid Unicode code point. + unsafe { core::hint::assert_unchecked(c <= char::MAX as Self) }; + + c } }