Skip to content

Commit 5c0f5b6

Browse files
authored
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``
2 parents 7cf2056 + e8cb72c commit 5c0f5b6

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

library/core/src/char/convert.rs

+42
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,48 @@ impl From<char> for u32 {
113113
}
114114
}
115115

116+
#[stable(feature = "more_char_conversions", since = "1.51.0")]
117+
impl From<char> for u64 {
118+
/// Converts a [`char`] into a [`u64`].
119+
///
120+
/// # Examples
121+
///
122+
/// ```
123+
/// use std::mem;
124+
///
125+
/// let c = '👤';
126+
/// let u = u64::from(c);
127+
/// assert!(8 == mem::size_of_val(&u))
128+
/// ```
129+
#[inline]
130+
fn from(c: char) -> Self {
131+
// The char is casted to the value of the code point, then zero-extended to 64 bit.
132+
// See [https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics]
133+
c as u64
134+
}
135+
}
136+
137+
#[stable(feature = "more_char_conversions", since = "1.51.0")]
138+
impl From<char> for u128 {
139+
/// Converts a [`char`] into a [`u128`].
140+
///
141+
/// # Examples
142+
///
143+
/// ```
144+
/// use std::mem;
145+
///
146+
/// let c = '⚙';
147+
/// let u = u128::from(c);
148+
/// assert!(16 == mem::size_of_val(&u))
149+
/// ```
150+
#[inline]
151+
fn from(c: char) -> Self {
152+
// The char is casted to the value of the code point, then zero-extended to 128 bit.
153+
// See [https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics]
154+
c as u128
155+
}
156+
}
157+
116158
/// Maps a byte in 0x00..=0xFF to a `char` whose code point has the same value, in U+0000..=U+00FF.
117159
///
118160
/// Unicode is designed such that this effectively decodes bytes

0 commit comments

Comments
 (0)