|
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.
|
@@ -176,6 +172,41 @@ pub unsafe fn from_u32_unchecked(i: u32) -> char {
|
176 | 172 | transmute(i)
|
177 | 173 | }
|
178 | 174 |
|
| 175 | +#[stable(feature = "char_convert", since = "1.12.0")] |
| 176 | +impl From<char> for u32 { |
| 177 | + #[inline] |
| 178 | + fn from(c: char) -> Self { |
| 179 | + c as u32 |
| 180 | + } |
| 181 | +} |
| 182 | + |
| 183 | +#[stable(feature = "char_convert", since = "1.12.0")] |
| 184 | +impl From<u8> for char { |
| 185 | + #[inline] |
| 186 | + fn from(i: u8) -> Self { |
| 187 | + i as char |
| 188 | + } |
| 189 | +} |
| 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 | + |
179 | 210 | /// Converts a digit in the given radix to a `char`.
|
180 | 211 | ///
|
181 | 212 | /// A 'radix' here is sometimes also called a 'base'. A radix of two
|
|
0 commit comments