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 /// For an unsafe version of this function which ignores these checks, see
27 /// [`from_u32_unchecked`].
36 /// let c = char::from_u32(0x2764);
38 /// assert_eq!(Some('❤'), c);
41 /// Returning `None` when the input is not a valid [`char`]:
46 /// let c = char::from_u32(0x110000);
48 /// assert_eq!(None, c);
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub fn from_u32(i: u32) -> Option<char> {
53 char::try_from(i).ok()
56 /// Converts a `u32` to a `char`, ignoring validity.
58 /// Note that all [`char`]s are valid [`u32`]s, and can be cast to one with
65 /// assert_eq!(128175, i);
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.
74 /// This function is unsafe, as it may construct invalid `char` values.
76 /// For a safe version of this function, see the [`from_u32`] function.
85 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
87 /// assert_eq!('❤', c);
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) } }
96 #[stable(feature = "char_convert", since = "1.13.0")]
97 impl From<char> for u32 {
98 /// Converts a [`char`] into a [`u32`].
106 /// let u = u32::from(c);
107 /// assert!(4 == mem::size_of_val(&u))
110 fn from(c: char) -> Self {
115 /// Maps a byte in 0x00..=0xFF to a `char` whose code point has the same value, in U+0000..=U+00FF.
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.
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.
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.
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`].
142 /// let u = 32 as u8;
143 /// let c = char::from(u);
144 /// assert!(4 == mem::size_of_val(&c))
147 fn from(i: u8) -> Self {
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 {
159 impl ParseCharError {
161 feature = "char_error_internals",
162 reason = "this method should not be available publicly",
166 pub fn __description(&self) -> &str {
168 CharErrorKind::EmptyString => "cannot parse char from empty string",
169 CharErrorKind::TooManyChars => "too many characters in string",
174 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
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)
187 #[stable(feature = "char_from_str", since = "1.20.0")]
188 impl FromStr for char {
189 type Err = ParseCharError;
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 }),
202 #[stable(feature = "try_from", since = "1.34.0")]
203 impl TryFrom<u32> for char {
204 type Error = CharTryFromError;
207 fn try_from(i: u32) -> Result<Self, Self::Error> {
208 if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
209 Err(CharTryFromError(()))
211 // SAFETY: checked that it's a legal unicode value
212 Ok(unsafe { transmute(i) })
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(());
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)
229 /// Converts a digit in the given radix to a `char`.
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.
236 /// `from_digit()` will return `None` if the input is not a digit in
241 /// Panics if given a radix larger than 36.
250 /// let c = char::from_digit(4, 10);
252 /// assert_eq!(Some('4'), c);
254 /// // Decimal 11 is a single digit in base 16
255 /// let c = char::from_digit(11, 16);
257 /// assert_eq!(Some('b'), c);
260 /// Returning `None` when the input is not a digit:
265 /// let c = char::from_digit(20, 10);
267 /// assert_eq!(None, c);
270 /// Passing a large radix, causing a panic:
276 /// let c = char::from_digit(1, 37);
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn from_digit(num: u32, radix: u32) -> Option<char> {
282 panic!("from_digit: radix is too high (maximum 36)");
286 if num < 10 { Some((b'0' + num) as char) } else { Some((b'a' + num - 10) as char) }