diff --git a/uefi/src/data_types/chars.rs b/uefi/src/data_types/chars.rs index 7d3b9a368..60671514b 100644 --- a/uefi/src/data_types/chars.rs +++ b/uefi/src/data_types/chars.rs @@ -27,18 +27,16 @@ impl TryFrom for Char8 { type Error = CharConversionError; fn try_from(value: char) -> Result { - let code_point = value as u32; - if code_point <= 0xff { - Ok(Char8(code_point as u8)) - } else { - Err(CharConversionError) - } + let code_point = u32::from(value); + u8::try_from(code_point) + .map(Char8) + .map_err(|_| CharConversionError) } } impl From for char { fn from(char: Char8) -> char { - char.0 as char + char::from(char.0) } } @@ -101,12 +99,10 @@ impl TryFrom for Char16 { type Error = CharConversionError; fn try_from(value: char) -> Result { - let code_point = value as u32; - if code_point <= 0xffff { - Ok(Char16(code_point as u16)) - } else { - Err(CharConversionError) - } + let code_point = u32::from(value); + u16::try_from(code_point) + .map(Char16) + .map_err(|_| CharConversionError) } } @@ -169,6 +165,17 @@ pub const NUL_16: Char16 = unsafe { Char16::from_u16_unchecked(0) }; mod tests { use super::*; + #[test] + fn test_char8_from_char() { + assert_eq!(Char8::try_from('A').unwrap(), Char8(0x41)); + } + + #[test] + fn test_char16_from_char() { + assert_eq!(Char16::try_from('A').unwrap(), Char16(0x41)); + assert_eq!(Char16::try_from('ꋃ').unwrap(), Char16(0xa2c3)); + } + /// Test that `Char8` and `Char16` can be directly compared with `char`. #[test] fn test_char_eq() { diff --git a/uefi/src/data_types/mod.rs b/uefi/src/data_types/mod.rs index f6c2d3cd0..0ddd31841 100644 --- a/uefi/src/data_types/mod.rs +++ b/uefi/src/data_types/mod.rs @@ -121,8 +121,7 @@ pub trait Align { /// is aligned. Returns `None` if no element of the buffer is /// aligned. fn align_buf(buf: &mut [u8]) -> Option<&mut [u8]> { - let addr = buf.as_ptr() as usize; - let offset = Self::offset_up_to_alignment(addr); + let offset = buf.as_ptr().align_offset(Self::alignment()); buf.get_mut(offset..) } @@ -130,7 +129,7 @@ pub trait Align { fn assert_aligned(storage: &mut [u8]) { if !storage.is_empty() { assert_eq!( - (storage.as_ptr() as usize) % Self::alignment(), + storage.as_ptr().align_offset(Self::alignment()), 0, "The provided storage is not correctly aligned for this type" ) diff --git a/uefi/src/data_types/strs.rs b/uefi/src/data_types/strs.rs index 209989a19..e3819dac1 100644 --- a/uefi/src/data_types/strs.rs +++ b/uefi/src/data_types/strs.rs @@ -504,7 +504,7 @@ impl From<&CStr16> for alloc::string::String { .iter() .copied() .map(u16::from) - .map(|int| int as u32) + .map(u32::from) .map(|int| char::from_u32(int).expect("Should be encodable as UTF-8")) .collect::() }