Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement TryFrom<char> for u8 #84640

Merged
merged 1 commit into from
Jan 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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