Skip to content

Commit cd9662b

Browse files
committed
Allow optimizing u32::from::<char>.
1 parent c3202af commit cd9662b

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

library/core/src/char/convert.rs

+18-3
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,12 @@ impl From<char> for u32 {
4848
/// ```
4949
#[inline]
5050
fn from(c: char) -> Self {
51-
c as u32
51+
let c = c as Self;
52+
53+
// SAFETY: `char::MAX` is the highest valid Unicode code point.
54+
unsafe { core::hint::assert_unchecked(c <= char::MAX as Self) };
55+
56+
c
5257
}
5358
}
5459

@@ -69,7 +74,12 @@ impl From<char> for u64 {
6974
fn from(c: char) -> Self {
7075
// The char is casted to the value of the code point, then zero-extended to 64 bit.
7176
// See [https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics]
72-
c as u64
77+
let c = c as Self;
78+
79+
// SAFETY: `char::MAX` is the highest valid Unicode code point.
80+
unsafe { core::hint::assert_unchecked(c <= char::MAX as Self) };
81+
82+
c
7383
}
7484
}
7585

@@ -90,7 +100,12 @@ impl From<char> for u128 {
90100
fn from(c: char) -> Self {
91101
// The char is casted to the value of the code point, then zero-extended to 128 bit.
92102
// See [https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics]
93-
c as u128
103+
let c = c as Self;
104+
105+
// SAFETY: `char::MAX` is the highest valid Unicode code point.
106+
unsafe { core::hint::assert_unchecked(c <= char::MAX as Self) };
107+
108+
c
94109
}
95110
}
96111

0 commit comments

Comments
 (0)