1 //! Character conversions.
3 use crate::convert::TryFrom;
5 use crate::mem::transmute;
6 use crate::str::FromStr;
10 /// Converts a `u32` to a `char`.
12 /// Note that all [`char`]s are valid [`u32`]s, and can be cast to one with
19 /// assert_eq!(128175, i);
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
26 /// [`char`]: ../../std/primitive.char.html
27 /// [`u32`]: ../../std/primitive.u32.html
29 /// For an unsafe version of this function which ignores these checks, see
30 /// [`from_u32_unchecked`].
32 /// [`from_u32_unchecked`]: fn.from_u32_unchecked.html
41 /// let c = char::from_u32(0x2764);
43 /// assert_eq!(Some('❤'), c);
46 /// Returning `None` when the input is not a valid [`char`]:
51 /// let c = char::from_u32(0x110000);
53 /// assert_eq!(None, c);
56 #[stable(feature = "rust1", since = "1.0.0")]
57 pub fn from_u32(i: u32) -> Option<char> {
58 char::try_from(i).ok()
61 /// Converts a `u32` to a `char`, ignoring validity.
63 /// Note that all [`char`]s are valid [`u32`]s, and can be cast to one with
70 /// assert_eq!(128175, i);
73 /// However, the reverse is not true: not all valid [`u32`]s are valid
74 /// [`char`]s. `from_u32_unchecked()` will ignore this, and blindly cast to
75 /// [`char`], possibly creating an invalid one.
77 /// [`char`]: ../../std/primitive.char.html
78 /// [`u32`]: ../../std/primitive.u32.html
82 /// This function is unsafe, as it may construct invalid `char` values.
84 /// For a safe version of this function, see the [`from_u32`] function.
86 /// [`from_u32`]: fn.from_u32.html
95 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
97 /// assert_eq!('❤', c);
100 #[stable(feature = "char_from_unchecked", since = "1.5.0")]
101 pub unsafe fn from_u32_unchecked(i: u32) -> char {
105 #[stable(feature = "char_convert", since = "1.13.0")]
106 impl From<char> for u32 {
107 /// Converts a [`char`] into a [`u32`].
115 /// let u = u32::from(c);
116 /// assert!(4 == mem::size_of_val(&u))
119 fn from(c: char) -> Self {
124 /// Maps a byte in 0x00..=0xFF to a `char` whose code point has the same value, in U+0000..=U+00FF.
126 /// Unicode is designed such that this effectively decodes bytes
127 /// with the character encoding that IANA calls ISO-8859-1.
128 /// This encoding is compatible with ASCII.
130 /// Note that this is different from ISO/IEC 8859-1 a.k.a. ISO 8859-1 (with one less hyphen),
131 /// which leaves some "blanks", byte values that are not assigned to any character.
132 /// ISO-8859-1 (the IANA one) assigns them to the C0 and C1 control codes.
134 /// Note that this is *also* different from Windows-1252 a.k.a. code page 1252,
135 /// which is a superset ISO/IEC 8859-1 that assigns some (not all!) blanks
136 /// to punctuation and various Latin characters.
138 /// To confuse things further, [on the Web](https://encoding.spec.whatwg.org/)
139 /// `ascii`, `iso-8859-1`, and `windows-1252` are all aliases
140 /// for a superset of Windows-1252 that fills the remaining blanks with corresponding
141 /// C0 and C1 control codes.
142 #[stable(feature = "char_convert", since = "1.13.0")]
143 impl From<u8> for char {
144 /// Converts a [`u8`] into a [`char`].
151 /// let u = 32 as u8;
152 /// let c = char::from(u);
153 /// assert!(4 == mem::size_of_val(&c))
156 fn from(i: u8) -> Self {
161 /// An error which can be returned when parsing a char.
162 #[stable(feature = "char_from_str", since = "1.20.0")]
163 #[derive(Clone, Debug, PartialEq, Eq)]
164 pub struct ParseCharError {
168 impl ParseCharError {
170 feature = "char_error_internals",
171 reason = "this method should not be available publicly",
175 pub fn __description(&self) -> &str {
177 CharErrorKind::EmptyString => "cannot parse char from empty string",
178 CharErrorKind::TooManyChars => "too many characters in string",
183 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
189 #[stable(feature = "char_from_str", since = "1.20.0")]
190 impl fmt::Display for ParseCharError {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 self.__description().fmt(f)
196 #[stable(feature = "char_from_str", since = "1.20.0")]
197 impl FromStr for char {
198 type Err = ParseCharError;
201 fn from_str(s: &str) -> Result<Self, Self::Err> {
202 let mut chars = s.chars();
203 match (chars.next(), chars.next()) {
204 (None, _) => Err(ParseCharError { kind: CharErrorKind::EmptyString }),
205 (Some(c), None) => Ok(c),
206 _ => Err(ParseCharError { kind: CharErrorKind::TooManyChars }),
211 #[stable(feature = "try_from", since = "1.34.0")]
212 impl TryFrom<u32> for char {
213 type Error = CharTryFromError;
216 fn try_from(i: u32) -> Result<Self, Self::Error> {
217 if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
218 Err(CharTryFromError(()))
220 // SAFETY: checked that it's a legal unicode value
221 Ok(unsafe { from_u32_unchecked(i) })
226 /// The error type returned when a conversion from u32 to char fails.
227 #[stable(feature = "try_from", since = "1.34.0")]
228 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
229 pub struct CharTryFromError(());
231 #[stable(feature = "try_from", since = "1.34.0")]
232 impl fmt::Display for CharTryFromError {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 "converted integer out of range for `char`".fmt(f)
238 /// Converts a digit in the given radix to a `char`.
240 /// A 'radix' here is sometimes also called a 'base'. A radix of two
241 /// indicates a binary number, a radix of ten, decimal, and a radix of
242 /// sixteen, hexadecimal, to give some common values. Arbitrary
243 /// radices are supported.
245 /// `from_digit()` will return `None` if the input is not a digit in
250 /// Panics if given a radix larger than 36.
259 /// let c = char::from_digit(4, 10);
261 /// assert_eq!(Some('4'), c);
263 /// // Decimal 11 is a single digit in base 16
264 /// let c = char::from_digit(11, 16);
266 /// assert_eq!(Some('b'), c);
269 /// Returning `None` when the input is not a digit:
274 /// let c = char::from_digit(20, 10);
276 /// assert_eq!(None, c);
279 /// Passing a large radix, causing a panic:
285 /// let result = thread::spawn(|| {
287 /// let c = char::from_digit(1, 37);
290 /// assert!(result.is_err());
293 #[stable(feature = "rust1", since = "1.0.0")]
294 pub fn from_digit(num: u32, radix: u32) -> Option<char> {
296 panic!("from_digit: radix is too high (maximum 36)");
300 if num < 10 { Some((b'0' + num) as char) } else { Some((b'a' + num - 10) as char) }