]> git.lizzy.rs Git - rust.git/blob - library/core/src/char/convert.rs
Rollup merge of #75485 - RalfJung:pin, r=nagisa
[rust.git] / library / core / src / char / convert.rs
1 //! Character conversions.
2
3 use crate::convert::TryFrom;
4 use crate::fmt;
5 use crate::mem::transmute;
6 use crate::str::FromStr;
7
8 use super::MAX;
9
10 /// Converts a `u32` to a `char`.
11 ///
12 /// Note that all [`char`]s are valid [`u32`]s, and can be cast to one with
13 /// `as`:
14 ///
15 /// ```
16 /// let c = '💯';
17 /// let i = c as u32;
18 ///
19 /// assert_eq!(128175, i);
20 /// ```
21 ///
22 /// However, the reverse is not true: not all valid [`u32`]s are valid
23 /// [`char`]s. `from_u32()` will return `None` if the input is not a valid value
24 /// for a [`char`].
25 ///
26 /// For an unsafe version of this function which ignores these checks, see
27 /// [`from_u32_unchecked`].
28 ///
29 /// # Examples
30 ///
31 /// Basic usage:
32 ///
33 /// ```
34 /// use std::char;
35 ///
36 /// let c = char::from_u32(0x2764);
37 ///
38 /// assert_eq!(Some('❤'), c);
39 /// ```
40 ///
41 /// Returning `None` when the input is not a valid [`char`]:
42 ///
43 /// ```
44 /// use std::char;
45 ///
46 /// let c = char::from_u32(0x110000);
47 ///
48 /// assert_eq!(None, c);
49 /// ```
50 #[inline]
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub fn from_u32(i: u32) -> Option<char> {
53     char::try_from(i).ok()
54 }
55
56 /// Converts a `u32` to a `char`, ignoring validity.
57 ///
58 /// Note that all [`char`]s are valid [`u32`]s, and can be cast to one with
59 /// `as`:
60 ///
61 /// ```
62 /// let c = '💯';
63 /// let i = c as u32;
64 ///
65 /// assert_eq!(128175, i);
66 /// ```
67 ///
68 /// However, the reverse is not true: not all valid [`u32`]s are valid
69 /// [`char`]s. `from_u32_unchecked()` will ignore this, and blindly cast to
70 /// [`char`], possibly creating an invalid one.
71 ///
72 /// # Safety
73 ///
74 /// This function is unsafe, as it may construct invalid `char` values.
75 ///
76 /// For a safe version of this function, see the [`from_u32`] function.
77 ///
78 /// # Examples
79 ///
80 /// Basic usage:
81 ///
82 /// ```
83 /// use std::char;
84 ///
85 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
86 ///
87 /// assert_eq!('❤', c);
88 /// ```
89 #[inline]
90 #[stable(feature = "char_from_unchecked", since = "1.5.0")]
91 pub unsafe fn from_u32_unchecked(i: u32) -> char {
92     // SAFETY: the caller must guarantee that `i` is a valid char value.
93     if cfg!(debug_assertions) { char::from_u32(i).unwrap() } else { unsafe { transmute(i) } }
94 }
95
96 #[stable(feature = "char_convert", since = "1.13.0")]
97 impl From<char> for u32 {
98     /// Converts a [`char`] into a [`u32`].
99     ///
100     /// # Examples
101     ///
102     /// ```
103     /// use std::mem;
104     ///
105     /// let c = 'c';
106     /// let u = u32::from(c);
107     /// assert!(4 == mem::size_of_val(&u))
108     /// ```
109     #[inline]
110     fn from(c: char) -> Self {
111         c as u32
112     }
113 }
114
115 /// Maps a byte in 0x00..=0xFF to a `char` whose code point has the same value, in U+0000..=U+00FF.
116 ///
117 /// Unicode is designed such that this effectively decodes bytes
118 /// with the character encoding that IANA calls ISO-8859-1.
119 /// This encoding is compatible with ASCII.
120 ///
121 /// Note that this is different from ISO/IEC 8859-1 a.k.a. ISO 8859-1 (with one less hyphen),
122 /// which leaves some "blanks", byte values that are not assigned to any character.
123 /// ISO-8859-1 (the IANA one) assigns them to the C0 and C1 control codes.
124 ///
125 /// Note that this is *also* different from Windows-1252 a.k.a. code page 1252,
126 /// which is a superset ISO/IEC 8859-1 that assigns some (not all!) blanks
127 /// to punctuation and various Latin characters.
128 ///
129 /// To confuse things further, [on the Web](https://encoding.spec.whatwg.org/)
130 /// `ascii`, `iso-8859-1`, and `windows-1252` are all aliases
131 /// for a superset of Windows-1252 that fills the remaining blanks with corresponding
132 /// C0 and C1 control codes.
133 #[stable(feature = "char_convert", since = "1.13.0")]
134 impl From<u8> for char {
135     /// Converts a [`u8`] into a [`char`].
136     ///
137     /// # Examples
138     ///
139     /// ```
140     /// use std::mem;
141     ///
142     /// let u = 32 as u8;
143     /// let c = char::from(u);
144     /// assert!(4 == mem::size_of_val(&c))
145     /// ```
146     #[inline]
147     fn from(i: u8) -> Self {
148         i as char
149     }
150 }
151
152 /// An error which can be returned when parsing a char.
153 #[stable(feature = "char_from_str", since = "1.20.0")]
154 #[derive(Clone, Debug, PartialEq, Eq)]
155 pub struct ParseCharError {
156     kind: CharErrorKind,
157 }
158
159 impl ParseCharError {
160     #[unstable(
161         feature = "char_error_internals",
162         reason = "this method should not be available publicly",
163         issue = "none"
164     )]
165     #[doc(hidden)]
166     pub fn __description(&self) -> &str {
167         match self.kind {
168             CharErrorKind::EmptyString => "cannot parse char from empty string",
169             CharErrorKind::TooManyChars => "too many characters in string",
170         }
171     }
172 }
173
174 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
175 enum CharErrorKind {
176     EmptyString,
177     TooManyChars,
178 }
179
180 #[stable(feature = "char_from_str", since = "1.20.0")]
181 impl fmt::Display for ParseCharError {
182     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183         self.__description().fmt(f)
184     }
185 }
186
187 #[stable(feature = "char_from_str", since = "1.20.0")]
188 impl FromStr for char {
189     type Err = ParseCharError;
190
191     #[inline]
192     fn from_str(s: &str) -> Result<Self, Self::Err> {
193         let mut chars = s.chars();
194         match (chars.next(), chars.next()) {
195             (None, _) => Err(ParseCharError { kind: CharErrorKind::EmptyString }),
196             (Some(c), None) => Ok(c),
197             _ => Err(ParseCharError { kind: CharErrorKind::TooManyChars }),
198         }
199     }
200 }
201
202 #[stable(feature = "try_from", since = "1.34.0")]
203 impl TryFrom<u32> for char {
204     type Error = CharTryFromError;
205
206     #[inline]
207     fn try_from(i: u32) -> Result<Self, Self::Error> {
208         if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
209             Err(CharTryFromError(()))
210         } else {
211             // SAFETY: checked that it's a legal unicode value
212             Ok(unsafe { transmute(i) })
213         }
214     }
215 }
216
217 /// The error type returned when a conversion from u32 to char fails.
218 #[stable(feature = "try_from", since = "1.34.0")]
219 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
220 pub struct CharTryFromError(());
221
222 #[stable(feature = "try_from", since = "1.34.0")]
223 impl fmt::Display for CharTryFromError {
224     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225         "converted integer out of range for `char`".fmt(f)
226     }
227 }
228
229 /// Converts a digit in the given radix to a `char`.
230 ///
231 /// A 'radix' here is sometimes also called a 'base'. A radix of two
232 /// indicates a binary number, a radix of ten, decimal, and a radix of
233 /// sixteen, hexadecimal, to give some common values. Arbitrary
234 /// radices are supported.
235 ///
236 /// `from_digit()` will return `None` if the input is not a digit in
237 /// the given radix.
238 ///
239 /// # Panics
240 ///
241 /// Panics if given a radix larger than 36.
242 ///
243 /// # Examples
244 ///
245 /// Basic usage:
246 ///
247 /// ```
248 /// use std::char;
249 ///
250 /// let c = char::from_digit(4, 10);
251 ///
252 /// assert_eq!(Some('4'), c);
253 ///
254 /// // Decimal 11 is a single digit in base 16
255 /// let c = char::from_digit(11, 16);
256 ///
257 /// assert_eq!(Some('b'), c);
258 /// ```
259 ///
260 /// Returning `None` when the input is not a digit:
261 ///
262 /// ```
263 /// use std::char;
264 ///
265 /// let c = char::from_digit(20, 10);
266 ///
267 /// assert_eq!(None, c);
268 /// ```
269 ///
270 /// Passing a large radix, causing a panic:
271 ///
272 /// ```should_panic
273 /// use std::char;
274 ///
275 /// // this panics
276 /// let c = char::from_digit(1, 37);
277 /// ```
278 #[inline]
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn from_digit(num: u32, radix: u32) -> Option<char> {
281     if radix > 36 {
282         panic!("from_digit: radix is too high (maximum 36)");
283     }
284     if num < radix {
285         let num = num as u8;
286         if num < 10 { Some((b'0' + num) as char) } else { Some((b'a' + num - 10) as char) }
287     } else {
288         None
289     }
290 }