|
16 | 16 | #![stable(feature = "core_char", since = "1.2.0")]
|
17 | 17 |
|
18 | 18 | use char_private::is_printable;
|
| 19 | +use convert::TryFrom; |
| 20 | +use fmt; |
19 | 21 | use iter::FusedIterator;
|
20 | 22 | use mem::transmute;
|
21 | 23 |
|
@@ -122,12 +124,7 @@ pub const MAX: char = '\u{10ffff}';
|
122 | 124 | #[inline]
|
123 | 125 | #[stable(feature = "rust1", since = "1.0.0")]
|
124 | 126 | pub fn from_u32(i: u32) -> Option<char> {
|
125 |
| - // catch out-of-bounds and surrogates |
126 |
| - if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) { |
127 |
| - None |
128 |
| - } else { |
129 |
| - Some(unsafe { from_u32_unchecked(i) }) |
130 |
| - } |
| 127 | + char::try_from(i).ok() |
131 | 128 | }
|
132 | 129 |
|
133 | 130 | /// Converts a `u32` to a `char`, ignoring validity.
|
@@ -209,6 +206,32 @@ impl From<u8> for char {
|
209 | 206 | }
|
210 | 207 | }
|
211 | 208 |
|
| 209 | +#[unstable(feature = "try_from", issue = "33417")] |
| 210 | +impl TryFrom<u32> for char { |
| 211 | + type Err = CharTryFromError; |
| 212 | + |
| 213 | + #[inline] |
| 214 | + fn try_from(i: u32) -> Result<Self, Self::Err> { |
| 215 | + if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) { |
| 216 | + Err(CharTryFromError(())) |
| 217 | + } else { |
| 218 | + Ok(unsafe { from_u32_unchecked(i) }) |
| 219 | + } |
| 220 | + } |
| 221 | +} |
| 222 | + |
| 223 | +/// The error type returned when a conversion from u32 to char fails. |
| 224 | +#[unstable(feature = "try_from", issue = "33417")] |
| 225 | +#[derive(Copy, Clone, Debug, PartialEq, Eq)] |
| 226 | +pub struct CharTryFromError(()); |
| 227 | + |
| 228 | +#[unstable(feature = "try_from", issue = "33417")] |
| 229 | +impl fmt::Display for CharTryFromError { |
| 230 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 231 | + "converted integer out of range for `char`".fmt(f) |
| 232 | + } |
| 233 | +} |
| 234 | + |
212 | 235 | /// Converts a digit in the given radix to a `char`.
|
213 | 236 | ///
|
214 | 237 | /// A 'radix' here is sometimes also called a 'base'. A radix of two
|
|
0 commit comments