Implement TryFrom<char> for u8

Previously suggested in https://github.com/rust-lang/rfcs/issues/2854.

It makes sense to have this since `char` implements `From<u8>`. Likewise
`u32`, `u64`, and `u128` (since #79502) implement `From<char>`.
This commit is contained in:
Ian Douglas Scott 2021-04-27 21:05:26 -07:00 committed by Ian Douglas Scott
parent e012a191d7
commit a02639dc09
3 changed files with 30 additions and 0 deletions

View File

@ -1,5 +1,6 @@
//! Character conversions.
use crate::char::TryFromCharError;
use crate::convert::TryFrom;
use crate::fmt;
use crate::mem::transmute;
@ -166,6 +167,20 @@ fn from(c: char) -> Self {
}
}
/// Map `char` with code point in U+0000..=U+00FF to byte in 0x00..=0xFF with same value, failing
/// if the code point is greater than U+00FF.
///
/// See [`impl From<u8> for char`](char#impl-From<u8>) for details on the encoding.
#[stable(feature = "u8_from_char", since = "1.59.0")]
impl TryFrom<char> for u8 {
type Error = TryFromCharError;
#[inline]
fn try_from(c: char) -> Result<u8, Self::Error> {
u8::try_from(u32::from(c)).map_err(|_| TryFromCharError(()))
}
}
/// Maps a byte in 0x00..=0xFF to a `char` whose code point has the same value, in U+0000..=U+00FF.
///
/// Unicode is designed such that this effectively decodes bytes

View File

@ -544,3 +544,15 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
/// The error type returned when a checked char conversion fails.
#[stable(feature = "u8_from_char", since = "1.59.0")]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct TryFromCharError(pub(crate) ());
#[stable(feature = "u8_from_char", since = "1.59.0")]
impl fmt::Display for TryFromCharError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
"unicode code point out of range".fmt(fmt)
}
}

View File

@ -478,6 +478,9 @@ fn description(&self) -> &str {
}
}
#[stable(feature = "u8_from_char", since = "1.59.0")]
impl Error for char::TryFromCharError {}
#[unstable(feature = "map_try_insert", issue = "82766")]
impl<'a, K: Debug + Ord, V: Debug> Error
for crate::collections::btree_map::OccupiedError<'a, K, V>