|
18 | 18 | use prelude::v1::*;
|
19 | 19 |
|
20 | 20 | use char_private::is_printable;
|
| 21 | +use convert::TryFrom; |
21 | 22 | use mem::transmute;
|
22 | 23 |
|
23 | 24 | // UTF-8 ranges and tags for encoding characters
|
@@ -123,12 +124,7 @@ pub const MAX: char = '\u{10ffff}';
|
123 | 124 | #[inline]
|
124 | 125 | #[stable(feature = "rust1", since = "1.0.0")]
|
125 | 126 | pub fn from_u32(i: u32) -> Option<char> {
|
126 |
| - // catch out-of-bounds and surrogates |
127 |
| - if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) { |
128 |
| - None |
129 |
| - } else { |
130 |
| - Some(unsafe { from_u32_unchecked(i) }) |
131 |
| - } |
| 127 | + char::try_from(i).ok() |
132 | 128 | }
|
133 | 129 |
|
134 | 130 | /// Converts a `u32` to a `char`, ignoring validity.
|
@@ -192,6 +188,25 @@ impl From<u8> for char {
|
192 | 188 | }
|
193 | 189 | }
|
194 | 190 |
|
| 191 | +#[unstable(feature = "try_from", issue = "33417")] |
| 192 | +impl TryFrom<u32> for char { |
| 193 | + type Err = CharTryFromError; |
| 194 | + |
| 195 | + #[inline] |
| 196 | + fn try_from(i: u32) -> Result<Self, Self::Err> { |
| 197 | + if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) { |
| 198 | + Err(CharTryFromError(())) |
| 199 | + } else { |
| 200 | + Ok(unsafe { from_u32_unchecked(i) }) |
| 201 | + } |
| 202 | + } |
| 203 | +} |
| 204 | + |
| 205 | +/// The error type returned when a conversion from u32 to char fails. |
| 206 | +#[unstable(feature = "try_from", issue = "33417")] |
| 207 | +#[derive(Copy, Clone, Debug, PartialEq, Eq)] |
| 208 | +pub struct CharTryFromError(()); |
| 209 | + |
195 | 210 | /// Converts a digit in the given radix to a `char`.
|
196 | 211 | ///
|
197 | 212 | /// A 'radix' here is sometimes also called a 'base'. A radix of two
|
|
0 commit comments