1 //! Character conversions.
3 use crate::char::TryFromCharError;
4 use crate::convert::TryFrom;
6 use crate::mem::transmute;
7 use crate::str::FromStr;
9 /// Converts a `u32` to a `char`. See [`char::from_u32`].
12 pub(super) const fn from_u32(i: u32) -> Option<char> {
13 // FIXME: once Result::ok is const fn, use it here
14 match char_try_from_u32(i) {
20 /// Converts a `u32` to a `char`, ignoring validity. See [`char::from_u32_unchecked`].
21 #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
24 pub(super) const unsafe fn from_u32_unchecked(i: u32) -> char {
25 // SAFETY: the caller must guarantee that `i` is a valid char value.
26 if cfg!(debug_assertions) { char::from_u32(i).unwrap() } else { unsafe { transmute(i) } }
29 #[stable(feature = "char_convert", since = "1.13.0")]
30 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
31 impl const From<char> for u32 {
32 /// Converts a [`char`] into a [`u32`].
40 /// let u = u32::from(c);
41 /// assert!(4 == mem::size_of_val(&u))
44 fn from(c: char) -> Self {
49 #[stable(feature = "more_char_conversions", since = "1.51.0")]
50 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
51 impl const From<char> for u64 {
52 /// Converts a [`char`] into a [`u64`].
60 /// let u = u64::from(c);
61 /// assert!(8 == mem::size_of_val(&u))
64 fn from(c: char) -> Self {
65 // The char is casted to the value of the code point, then zero-extended to 64 bit.
66 // See [https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics]
71 #[stable(feature = "more_char_conversions", since = "1.51.0")]
72 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
73 impl const From<char> for u128 {
74 /// Converts a [`char`] into a [`u128`].
82 /// let u = u128::from(c);
83 /// assert!(16 == mem::size_of_val(&u))
86 fn from(c: char) -> Self {
87 // The char is casted to the value of the code point, then zero-extended to 128 bit.
88 // See [https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics]
93 /// Map `char` with code point in U+0000..=U+00FF to byte in 0x00..=0xFF with same value, failing
94 /// if the code point is greater than U+00FF.
96 /// See [`impl From<u8> for char`](char#impl-From<u8>-for-char) for details on the encoding.
97 #[stable(feature = "u8_from_char", since = "1.59.0")]
98 impl TryFrom<char> for u8 {
99 type Error = TryFromCharError;
102 fn try_from(c: char) -> Result<u8, Self::Error> {
103 u8::try_from(u32::from(c)).map_err(|_| TryFromCharError(()))
107 /// Maps a byte in 0x00..=0xFF to a `char` whose code point has the same value, in U+0000..=U+00FF.
109 /// Unicode is designed such that this effectively decodes bytes
110 /// with the character encoding that IANA calls ISO-8859-1.
111 /// This encoding is compatible with ASCII.
113 /// Note that this is different from ISO/IEC 8859-1 a.k.a. ISO 8859-1 (with one less hyphen),
114 /// which leaves some "blanks", byte values that are not assigned to any character.
115 /// ISO-8859-1 (the IANA one) assigns them to the C0 and C1 control codes.
117 /// Note that this is *also* different from Windows-1252 a.k.a. code page 1252,
118 /// which is a superset ISO/IEC 8859-1 that assigns some (not all!) blanks
119 /// to punctuation and various Latin characters.
121 /// To confuse things further, [on the Web](https://encoding.spec.whatwg.org/)
122 /// `ascii`, `iso-8859-1`, and `windows-1252` are all aliases
123 /// for a superset of Windows-1252 that fills the remaining blanks with corresponding
124 /// C0 and C1 control codes.
125 #[stable(feature = "char_convert", since = "1.13.0")]
126 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
127 impl const From<u8> for char {
128 /// Converts a [`u8`] into a [`char`].
135 /// let u = 32 as u8;
136 /// let c = char::from(u);
137 /// assert!(4 == mem::size_of_val(&c))
140 fn from(i: u8) -> Self {
145 /// An error which can be returned when parsing a char.
147 /// This `struct` is created when using the [`char::from_str`] method.
148 #[stable(feature = "char_from_str", since = "1.20.0")]
149 #[derive(Clone, Debug, PartialEq, Eq)]
150 pub struct ParseCharError {
154 impl ParseCharError {
156 feature = "char_error_internals",
157 reason = "this method should not be available publicly",
161 pub fn __description(&self) -> &str {
163 CharErrorKind::EmptyString => "cannot parse char from empty string",
164 CharErrorKind::TooManyChars => "too many characters in string",
169 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
175 #[stable(feature = "char_from_str", since = "1.20.0")]
176 impl fmt::Display for ParseCharError {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 self.__description().fmt(f)
182 #[stable(feature = "char_from_str", since = "1.20.0")]
183 impl FromStr for char {
184 type Err = ParseCharError;
187 fn from_str(s: &str) -> Result<Self, Self::Err> {
188 let mut chars = s.chars();
189 match (chars.next(), chars.next()) {
190 (None, _) => Err(ParseCharError { kind: CharErrorKind::EmptyString }),
191 (Some(c), None) => Ok(c),
192 _ => Err(ParseCharError { kind: CharErrorKind::TooManyChars }),
198 const fn char_try_from_u32(i: u32) -> Result<char, CharTryFromError> {
199 // This is an optimized version of the check
200 // (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF),
201 // which can also be written as
202 // i >= 0x110000 || (i >= 0xD800 && i < 0xE000).
204 // The XOR with 0xD800 permutes the ranges such that 0xD800..0xE000 is
205 // mapped to 0x0000..0x0800, while keeping all the high bits outside 0xFFFF the same.
206 // In particular, numbers >= 0x110000 stay in this range.
208 // Subtracting 0x800 causes 0x0000..0x0800 to wrap, meaning that a single
209 // unsigned comparison against 0x110000 - 0x800 will detect both the wrapped
210 // surrogate range as well as the numbers originally larger than 0x110000.
212 if (i ^ 0xD800).wrapping_sub(0x800) >= 0x110000 - 0x800 {
213 Err(CharTryFromError(()))
215 // SAFETY: checked that it's a legal unicode value
216 Ok(unsafe { transmute(i) })
220 #[stable(feature = "try_from", since = "1.34.0")]
221 impl TryFrom<u32> for char {
222 type Error = CharTryFromError;
225 fn try_from(i: u32) -> Result<Self, Self::Error> {
230 /// The error type returned when a conversion from [`prim@u32`] to [`prim@char`] fails.
232 /// This `struct` is created by the [`char::try_from<u32>`](char#impl-TryFrom<u32>-for-char) method.
233 /// See its documentation for more.
234 #[stable(feature = "try_from", since = "1.34.0")]
235 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
236 pub struct CharTryFromError(());
238 #[stable(feature = "try_from", since = "1.34.0")]
239 impl fmt::Display for CharTryFromError {
240 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241 "converted integer out of range for `char`".fmt(f)
245 /// Converts a digit in the given radix to a `char`. See [`char::from_digit`].
248 pub(super) const fn from_digit(num: u32, radix: u32) -> Option<char> {
250 panic!("from_digit: radix is too high (maximum 36)");
254 if num < 10 { Some((b'0' + num) as char) } else { Some((b'a' + num - 10) as char) }