Skip to content

Commit 2d8d2a1

Browse files
committed
Implement From<char> for u32, and From<u8> for char
These fit with other From implementations between integer types. This helps the coding style of avoiding the 'as' operator that sometimes silently truncates, and signals that these specific conversions are lossless and infaillible.
1 parent 6c0d66a commit 2d8d2a1

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

Diff for: src/libcore/char.rs

+16
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,22 @@ pub unsafe fn from_u32_unchecked(i: u32) -> char {
176176
transmute(i)
177177
}
178178

179+
#[stable(feature = "char_convert", since = "1.12.0")]
180+
impl From<char> for u32 {
181+
#[inline]
182+
fn from(c: char) -> Self {
183+
c as u32
184+
}
185+
}
186+
187+
#[stable(feature = "char_convert", since = "1.12.0")]
188+
impl From<u8> for char {
189+
#[inline]
190+
fn from(i: u8) -> Self {
191+
i as char
192+
}
193+
}
194+
179195
/// Converts a digit in the given radix to a `char`.
180196
///
181197
/// A 'radix' here is sometimes also called a 'base'. A radix of two

Diff for: src/libcoretest/char.rs

+8
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@
1010

1111
use std::char;
1212

13+
#[test]
14+
fn test_convert() {
15+
assert_eq!(u32::from('a'), 0x61);
16+
assert_eq!(char::from(b'\0'), '\0');
17+
assert_eq!(char::from(b'a'), 'a');
18+
assert_eq!(char::from(b'\xFF'), '\u{FF}');
19+
}
20+
1321
#[test]
1422
fn test_is_lowercase() {
1523
assert!('a'.is_lowercase());

0 commit comments

Comments
 (0)