Skip to content

Commit

Permalink
Implement TryFrom<char> for u8
Browse files Browse the repository at this point in the history
Previously suggested in rust-lang/rfcs#2854.

It makes sense to have this since `char` implements `From<u8>`. Likewise
`u32`, `u64`, and `u128` (since rust-lang#79502) implement `From<char>`.
  • Loading branch information
ids1024 committed Jan 7, 2022
1 parent e012a19 commit a02639d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
15 changes: 15 additions & 0 deletions library/core/src/char/convert.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Character conversions.

use crate::char::TryFromCharError;
use crate::convert::TryFrom;
use crate::fmt;
use crate::mem::transmute;
Expand Down Expand Up @@ -166,6 +167,20 @@ impl const From<char> for u128 {
}
}

/// 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
Expand Down
12 changes: 12 additions & 0 deletions library/core/src/char/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,3 +544,15 @@ impl fmt::Display for ToUppercase {
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)
}
}
3 changes: 3 additions & 0 deletions library/std/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,9 @@ impl Error for char::DecodeUtf16Error {
}
}

#[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>
Expand Down

0 comments on commit a02639d

Please sign in to comment.