Skip to content

Commit 8c070c7

Browse files
phip1611nicholasbishop
authored andcommitted
TryFrom<core::ffi::CStr> implementation for CStr8
After this was reverted in 5f4e158, we now can add it again, as our MSRV is now recent enough.
1 parent 48d2159 commit 8c070c7

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
- Implementations for the trait `EqStrUntilNul` now allow `?Sized` inputs. This means that
55
you can write `some_cstr16.eq_str_until_nul("test")` instead of
66
`some_cstr16.eq_str_until_nul(&"test")` now.
7+
- Added `TryFrom<core::ffi::CStr>` implementation for `CStr8`.
78

89
## uefi-macros - [Unreleased]
910

uefi/src/data_types/strs.rs

+24
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use super::chars::{Char16, Char8, NUL_16, NUL_8};
22
use super::UnalignedSlice;
3+
use core::ffi::CStr;
34
use core::fmt;
45
use core::iter::Iterator;
56
use core::mem::MaybeUninit;
@@ -58,6 +59,11 @@ pub enum FromStrWithBufError {
5859
/// This type is largely inspired by [`core::ffi::CStr`] with the exception that all characters are
5960
/// guaranteed to be 8 bit long.
6061
///
62+
/// A [`CStr8`] can be constructed from a [`core::ffi::CStr`] via a `try_from` call:
63+
/// ```ignore
64+
/// let cstr8: &CStr8 = TryFrom::try_from(cstr).unwrap();
65+
/// ```
66+
///
6167
/// For convenience, a [`CStr8`] is comparable with [`core::str`] and
6268
/// `alloc::string::String` from the standard library through the trait [`EqStrUntilNul`].
6369
#[repr(transparent)]
@@ -156,6 +162,14 @@ impl<StrType: AsRef<str> + ?Sized> EqStrUntilNul<StrType> for CStr8 {
156162
}
157163
}
158164

165+
impl<'a> TryFrom<&'a CStr> for &'a CStr8 {
166+
type Error = FromSliceWithNulError;
167+
168+
fn try_from(cstr: &'a CStr) -> Result<Self, Self::Error> {
169+
CStr8::from_bytes_with_nul(cstr.to_bytes_with_nul())
170+
}
171+
}
172+
159173
/// An UCS-2 null-terminated string.
160174
///
161175
/// This type is largely inspired by [`core::ffi::CStr`] with the exception that all characters are
@@ -453,6 +467,16 @@ mod tests {
453467
use crate::alloc::string::String;
454468
use uefi_macros::{cstr16, cstr8};
455469

470+
// Tests if our CStr8 type can be constructed from a valid core::ffi::CStr
471+
#[test]
472+
fn test_cstr8_from_cstr() {
473+
let msg = "hello world\0";
474+
let cstr = unsafe { CStr::from_ptr(msg.as_ptr().cast()) };
475+
let cstr8: &CStr8 = TryFrom::try_from(cstr).unwrap();
476+
assert!(cstr8.eq_str_until_nul(msg));
477+
assert!(msg.eq_str_until_nul(cstr8));
478+
}
479+
456480
#[test]
457481
fn test_cstr16_num_bytes() {
458482
let s = CStr16::from_u16_with_nul(&[65, 66, 67, 0]).unwrap();

0 commit comments

Comments
 (0)