Skip to content

Commit a02639d

Browse files
committed
Implement TryFrom<char> for u8
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>`.
1 parent e012a19 commit a02639d

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

library/core/src/char/convert.rs

+15
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! Character conversions.
22
3+
use crate::char::TryFromCharError;
34
use crate::convert::TryFrom;
45
use crate::fmt;
56
use crate::mem::transmute;
@@ -166,6 +167,20 @@ impl const From<char> for u128 {
166167
}
167168
}
168169

170+
/// Map `char` with code point in U+0000..=U+00FF to byte in 0x00..=0xFF with same value, failing
171+
/// if the code point is greater than U+00FF.
172+
///
173+
/// See [`impl From<u8> for char`](char#impl-From<u8>) for details on the encoding.
174+
#[stable(feature = "u8_from_char", since = "1.59.0")]
175+
impl TryFrom<char> for u8 {
176+
type Error = TryFromCharError;
177+
178+
#[inline]
179+
fn try_from(c: char) -> Result<u8, Self::Error> {
180+
u8::try_from(u32::from(c)).map_err(|_| TryFromCharError(()))
181+
}
182+
}
183+
169184
/// Maps a byte in 0x00..=0xFF to a `char` whose code point has the same value, in U+0000..=U+00FF.
170185
///
171186
/// Unicode is designed such that this effectively decodes bytes

library/core/src/char/mod.rs

+12
Original file line numberDiff line numberDiff line change
@@ -544,3 +544,15 @@ impl fmt::Display for ToUppercase {
544544
fmt::Display::fmt(&self.0, f)
545545
}
546546
}
547+
548+
/// The error type returned when a checked char conversion fails.
549+
#[stable(feature = "u8_from_char", since = "1.59.0")]
550+
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
551+
pub struct TryFromCharError(pub(crate) ());
552+
553+
#[stable(feature = "u8_from_char", since = "1.59.0")]
554+
impl fmt::Display for TryFromCharError {
555+
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
556+
"unicode code point out of range".fmt(fmt)
557+
}
558+
}

library/std/src/error.rs

+3
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,9 @@ impl Error for char::DecodeUtf16Error {
478478
}
479479
}
480480

481+
#[stable(feature = "u8_from_char", since = "1.59.0")]
482+
impl Error for char::TryFromCharError {}
483+
481484
#[unstable(feature = "map_try_insert", issue = "82766")]
482485
impl<'a, K: Debug + Ord, V: Debug> Error
483486
for crate::collections::btree_map::OccupiedError<'a, K, V>

0 commit comments

Comments
 (0)