diff options
| author | Simon Sapin <simon.sapin@exyr.org> | 2016-08-17 18:01:41 +0200 |
|---|---|---|
| committer | Simon Sapin <simon.sapin@exyr.org> | 2016-08-29 17:34:02 +0200 |
| commit | f040208d533e1d6d9ee0e0408ee74e26e14d1284 (patch) | |
| tree | 5592063ace04a7f2016e6398094b66b7e4ad521b /src/libcore | |
| parent | 41d0a89e3ad99a9fdf700ea7d15750fe1cbfab14 (diff) | |
| download | rust-f040208d533e1d6d9ee0e0408ee74e26e14d1284.tar.gz rust-f040208d533e1d6d9ee0e0408ee74e26e14d1284.zip | |
Implement TryFrom<u32> for char
For symmetry with From<char> for u32.
Diffstat (limited to 'src/libcore')
| -rw-r--r-- | src/libcore/char.rs | 35 |
1 files changed, 29 insertions, 6 deletions
diff --git a/src/libcore/char.rs b/src/libcore/char.rs index 47a8678d608..ad492c81bd3 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -16,6 +16,8 @@ #![stable(feature = "core_char", since = "1.2.0")] use char_private::is_printable; +use convert::TryFrom; +use fmt; use iter::FusedIterator; use mem::transmute; @@ -122,12 +124,7 @@ pub const MAX: char = '\u{10ffff}'; #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_u32(i: u32) -> Option<char> { - // catch out-of-bounds and surrogates - if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) { - None - } else { - Some(unsafe { from_u32_unchecked(i) }) - } + char::try_from(i).ok() } /// Converts a `u32` to a `char`, ignoring validity. @@ -209,6 +206,32 @@ impl From<u8> for char { } } +#[unstable(feature = "try_from", issue = "33417")] +impl TryFrom<u32> for char { + type Err = CharTryFromError; + + #[inline] + fn try_from(i: u32) -> Result<Self, Self::Err> { + if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) { + Err(CharTryFromError(())) + } else { + Ok(unsafe { from_u32_unchecked(i) }) + } + } +} + +/// The error type returned when a conversion from u32 to char fails. +#[unstable(feature = "try_from", issue = "33417")] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct CharTryFromError(()); + +#[unstable(feature = "try_from", issue = "33417")] +impl fmt::Display for CharTryFromError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "converted integer out of range for `char`".fmt(f) + } +} + /// Converts a digit in the given radix to a `char`. /// /// A 'radix' here is sometimes also called a 'base'. A radix of two |
