Skip to content

Commit

Permalink
Allow optimizing u32::from::<char>.
Browse files Browse the repository at this point in the history
  • Loading branch information
reitermarkus committed May 8, 2024
1 parent 57c84a5 commit ec1775d
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions library/core/src/char/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,12 @@ impl From<char> 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
}
}

Expand All @@ -69,7 +74,12 @@ impl From<char> 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
}
}

Expand All @@ -90,7 +100,12 @@ impl From<char> 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
}
}

Expand Down

0 comments on commit ec1775d

Please sign in to comment.