Skip to content

Commit 604a03c

Browse files
uefi: Improve char conversions
Remove some uses of `as` and add some more tests.
1 parent 7e18c2d commit 604a03c

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

uefi/src/data_types/chars.rs

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,18 +27,14 @@ impl TryFrom<char> for Char8 {
2727
type Error = CharConversionError;
2828

2929
fn try_from(value: char) -> Result<Self, Self::Error> {
30-
let code_point = value as u32;
31-
if code_point <= 0xff {
32-
Ok(Char8(code_point as u8))
33-
} else {
34-
Err(CharConversionError)
35-
}
30+
let code_point = u32::from(value);
31+
u8::try_from(code_point).map(Char8).map_err(|_| CharConversionError)
3632
}
3733
}
3834

3935
impl From<Char8> for char {
4036
fn from(char: Char8) -> char {
41-
char.0 as char
37+
char::from(char.0)
4238
}
4339
}
4440

@@ -101,12 +97,8 @@ impl TryFrom<char> for Char16 {
10197
type Error = CharConversionError;
10298

10399
fn try_from(value: char) -> Result<Self, Self::Error> {
104-
let code_point = value as u32;
105-
if code_point <= 0xffff {
106-
Ok(Char16(code_point as u16))
107-
} else {
108-
Err(CharConversionError)
109-
}
100+
let code_point = u32::from(value);
101+
u16::try_from(code_point).map(Char16).map_err(|_| CharConversionError)
110102
}
111103
}
112104

@@ -169,6 +161,17 @@ pub const NUL_16: Char16 = unsafe { Char16::from_u16_unchecked(0) };
169161
mod tests {
170162
use super::*;
171163

164+
#[test]
165+
fn test_char8_from_char() {
166+
assert_eq!(Char8::try_from('A').unwrap(), Char8(0x41));
167+
}
168+
169+
#[test]
170+
fn test_char16_from_char() {
171+
assert_eq!(Char16::try_from('A').unwrap(), Char16(0x41));
172+
assert_eq!(Char16::try_from('ꋃ').unwrap(), Char16(0xa2c3));
173+
}
174+
172175
/// Test that `Char8` and `Char16` can be directly compared with `char`.
173176
#[test]
174177
fn test_char_eq() {

0 commit comments

Comments
 (0)