]> git.lizzy.rs Git - rust.git/blob - library/core/src/char/convert.rs
Auto merge of #98843 - Urgau:check-cfg-stage0, r=Mark-Simulacrum
[rust.git] / library / core / src / char / convert.rs
1 //! Character conversions.
2
3 use crate::char::TryFromCharError;
4 use crate::convert::TryFrom;
5 use crate::fmt;
6 use crate::mem::transmute;
7 use crate::str::FromStr;
8
9 /// Converts a `u32` to a `char`. See [`char::from_u32`].
10 #[must_use]
11 #[inline]
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) {
15         Ok(c) => Some(c),
16         Err(_) => None,
17     }
18 }
19
20 /// Converts a `u32` to a `char`, ignoring validity. See [`char::from_u32_unchecked`].
21 #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
22 #[inline]
23 #[must_use]
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) } }
27 }
28
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`].
33     ///
34     /// # Examples
35     ///
36     /// ```
37     /// use std::mem;
38     ///
39     /// let c = 'c';
40     /// let u = u32::from(c);
41     /// assert!(4 == mem::size_of_val(&u))
42     /// ```
43     #[inline]
44     fn from(c: char) -> Self {
45         c as u32
46     }
47 }
48
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`].
53     ///
54     /// # Examples
55     ///
56     /// ```
57     /// use std::mem;
58     ///
59     /// let c = '👤';
60     /// let u = u64::from(c);
61     /// assert!(8 == mem::size_of_val(&u))
62     /// ```
63     #[inline]
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]
67         c as u64
68     }
69 }
70
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`].
75     ///
76     /// # Examples
77     ///
78     /// ```
79     /// use std::mem;
80     ///
81     /// let c = 'âš™';
82     /// let u = u128::from(c);
83     /// assert!(16 == mem::size_of_val(&u))
84     /// ```
85     #[inline]
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]
89         c as u128
90     }
91 }
92
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.
95 ///
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;
100
101     #[inline]
102     fn try_from(c: char) -> Result<u8, Self::Error> {
103         u8::try_from(u32::from(c)).map_err(|_| TryFromCharError(()))
104     }
105 }
106
107 /// Maps a byte in 0x00..=0xFF to a `char` whose code point has the same value, in U+0000..=U+00FF.
108 ///
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.
112 ///
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.
116 ///
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.
120 ///
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`].
129     ///
130     /// # Examples
131     ///
132     /// ```
133     /// use std::mem;
134     ///
135     /// let u = 32 as u8;
136     /// let c = char::from(u);
137     /// assert!(4 == mem::size_of_val(&c))
138     /// ```
139     #[inline]
140     fn from(i: u8) -> Self {
141         i as char
142     }
143 }
144
145 /// An error which can be returned when parsing a char.
146 ///
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 {
151     kind: CharErrorKind,
152 }
153
154 impl ParseCharError {
155     #[unstable(
156         feature = "char_error_internals",
157         reason = "this method should not be available publicly",
158         issue = "none"
159     )]
160     #[doc(hidden)]
161     pub fn __description(&self) -> &str {
162         match self.kind {
163             CharErrorKind::EmptyString => "cannot parse char from empty string",
164             CharErrorKind::TooManyChars => "too many characters in string",
165         }
166     }
167 }
168
169 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
170 enum CharErrorKind {
171     EmptyString,
172     TooManyChars,
173 }
174
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)
179     }
180 }
181
182 #[stable(feature = "char_from_str", since = "1.20.0")]
183 impl FromStr for char {
184     type Err = ParseCharError;
185
186     #[inline]
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 }),
193         }
194     }
195 }
196
197 #[inline]
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).
203     //
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.
207     //
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.
211     //
212     if (i ^ 0xD800).wrapping_sub(0x800) >= 0x110000 - 0x800 {
213         Err(CharTryFromError(()))
214     } else {
215         // SAFETY: checked that it's a legal unicode value
216         Ok(unsafe { transmute(i) })
217     }
218 }
219
220 #[stable(feature = "try_from", since = "1.34.0")]
221 impl TryFrom<u32> for char {
222     type Error = CharTryFromError;
223
224     #[inline]
225     fn try_from(i: u32) -> Result<Self, Self::Error> {
226         char_try_from_u32(i)
227     }
228 }
229
230 /// The error type returned when a conversion from [`prim@u32`] to [`prim@char`] fails.
231 ///
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(());
237
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)
242     }
243 }
244
245 /// Converts a digit in the given radix to a `char`. See [`char::from_digit`].
246 #[inline]
247 #[must_use]
248 pub(super) const fn from_digit(num: u32, radix: u32) -> Option<char> {
249     if radix > 36 {
250         panic!("from_digit: radix is too high (maximum 36)");
251     }
252     if num < radix {
253         let num = num as u8;
254         if num < 10 { Some((b'0' + num) as char) } else { Some((b'a' + num - 10) as char) }
255     } else {
256         None
257     }
258 }