Skip to content

Commit 4bf6535

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

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

uefi/src/data_types/chars.rs

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,18 +27,16 @@ 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)
32+
.map(Char8)
33+
.map_err(|_| CharConversionError)
3634
}
3735
}
3836

3937
impl From<Char8> for char {
4038
fn from(char: Char8) -> char {
41-
char.0 as char
39+
char::from(char.0)
4240
}
4341
}
4442

@@ -101,12 +99,10 @@ impl TryFrom<char> for Char16 {
10199
type Error = CharConversionError;
102100

103101
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-
}
102+
let code_point = u32::from(value);
103+
u16::try_from(code_point)
104+
.map(Char16)
105+
.map_err(|_| CharConversionError)
110106
}
111107
}
112108

@@ -169,6 +165,17 @@ pub const NUL_16: Char16 = unsafe { Char16::from_u16_unchecked(0) };
169165
mod tests {
170166
use super::*;
171167

168+
#[test]
169+
fn test_char8_from_char() {
170+
assert_eq!(Char8::try_from('A').unwrap(), Char8(0x41));
171+
}
172+
173+
#[test]
174+
fn test_char16_from_char() {
175+
assert_eq!(Char16::try_from('A').unwrap(), Char16(0x41));
176+
assert_eq!(Char16::try_from('ꋃ').unwrap(), Char16(0xa2c3));
177+
}
178+
172179
/// Test that `Char8` and `Char16` can be directly compared with `char`.
173180
#[test]
174181
fn test_char_eq() {

0 commit comments

Comments
 (0)