Rollup merge of #79502 - Julian-Wollersberger:from_char_for_u64, r=withoutboats

Implement From<char> for u64 and u128.

With this PR you can write
```
let u = u64::from('👤');
let u = u128::from('👤');
```

Previously, you could already write `as` conversions ([Playground link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=cee18febe28e69024357d099f07ca081)):
```
// Lossless conversions
dbg!('👤' as u32);    // Prints 128100
dbg!('👤' as u64);    // Prints 128100
dbg!('👤' as u128);   // Prints 128100

// truncates, thus no `From` impls.
dbg!('👤' as u8);     // Prints 100
dbg!('👤' as u16);    // Prints 62564

// These `From` impls already exist.
dbg!(u32::from('👤'));               // Prints 128100
dbg!(u64::from(u32::from('👤')));    // Prints 128100
```

The idea is from ``@gendx`` who opened [this Internals thread](https://internals.rust-lang.org/t/implement-from-char-for-u64/13454), and ``@withoutboats`` responded that someone should open a PR for it.
Some people mentioned `From<char>` impls for `f32` and `f64`, but that doesn't seem correct to me, so I didn't include them here.

I don't know what the feature should be named. Must it be registered somewhere, like unstable features?

r? ``@withoutboats``
This commit is contained in:
Yuki Okushi 2021-01-10 16:55:53 +09:00 committed by GitHub
commit 5c0f5b69c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -113,6 +113,48 @@ fn from(c: char) -> Self {
}
}
#[stable(feature = "more_char_conversions", since = "1.51.0")]
impl From<char> for u64 {
/// Converts a [`char`] into a [`u64`].
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let c = '👤';
/// let u = u64::from(c);
/// assert!(8 == mem::size_of_val(&u))
/// ```
#[inline]
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
}
}
#[stable(feature = "more_char_conversions", since = "1.51.0")]
impl From<char> for u128 {
/// Converts a [`char`] into a [`u128`].
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let c = '⚙';
/// let u = u128::from(c);
/// assert!(16 == mem::size_of_val(&u))
/// ```
#[inline]
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
}
}
/// Maps a byte in 0x00..=0xFF to a `char` whose code point has the same value, in U+0000..=U+00FF.
///
/// Unicode is designed such that this effectively decodes bytes